You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

47 lines
1.6 KiB
C#

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
namespace DSWeb.Helper
{
public static class RedisHelper
{
/// <summary>
/// 根据当前web.config配置向redis写入值
/// </summary>
public static void Set(string key, string content, int expireSeconds = 120)
{
ConnectionMultiplexer redis = ConnectionMultiplexer.Connect(ConfigurationManager.AppSettings["RedisServerAddr"]);
var strDbIdx = ConfigurationManager.AppSettings["RedisServerDB"];
var dbIdx = string.IsNullOrEmpty(strDbIdx) ? -1 : Convert.ToInt32(strDbIdx);
IDatabase db = redis.GetDatabase(dbIdx);
db.StringSet(key, content, expiry: new TimeSpan(0, 0, expireSeconds));
redis.Close();
}
/// <summary>
/// 根据当前web.config配置从redis读取值
/// </summary>
/// <returns></returns>
public static string Get(string key)
{
ConnectionMultiplexer redis = ConnectionMultiplexer.Connect(ConfigurationManager.AppSettings["RedisServerAddr"]);
var strDbIdx = ConfigurationManager.AppSettings["RedisServerDB"];
var dbIdx = string.IsNullOrEmpty(strDbIdx) ? -1 : Convert.ToInt32(strDbIdx);
IDatabase db = redis.GetDatabase(dbIdx);
string val = null;
if (db.KeyExists(key))
{
val = db.StringGet(key);
}
redis.Close();
return val;
}
}
}