public class RedisManager
{
/// <summary>
/// redis配置文件信息
/// </summary>
private static RedisConfig RedisConfig = RedisConfig.GetConfig();
private static ConnectionMultiplexer _redis;
private static object _locker = new object();
public static ConnectionMultiplexer Manager
{
get
{
if (_redis == null)
{
lock (_locker)
{
if (_redis != null) return _redis;
_redis = GetManager();
return _redis;
}
}
return _redis;
}
}
private static ConnectionMultiplexer GetManager(ConfigurationOptions configurationOptions = null)
{
if (configurationOptions == null)
{
configurationOptions = new ConfigurationOptions()
{
EndPoints = { { RedisConfig.WriteServerConStr } },
CommandMap = CommandMap.Create(new HashSet<string>()
{
"INFO",
"CONFIG",
"CLUSTER",
"PING",
"ECHO",
"CLIENT"
}, available: false),
KeepAlive = RedisConfig.KeepAlive,
DefaultVersion = new Version(2, 8, 24),
Password = RedisConfig.PassWord
};
}
return ConnectionMultiplexer.Connect(configurationOptions);
}
}
public class RedisCacheManager : ICacheManager
{
public static RedisCacheManager Instance = new RedisCacheManager();
public string Get(string key)
{
var db = RedisManager.Manager.GetDatabase();
return db.StringGet(key);
}
public T Get<T>(string key)
{
var db = RedisManager.Manager.GetDatabase();
return JsonConvert.DeserializeObject<T>(db.StringGet(key));
}
public void Set<T>(string key, T data, int cacheTime)
{
var db = RedisManager.Manager.GetDatabase();
string str = JsonConvert.SerializeObject(data);
db.StringSet(key, str, TimeSpan.FromMinutes(cacheTime));
}
public void Set(string key, object data, int cacheTime)
{
var db = RedisManager.Manager.GetDatabase();
string str = JsonConvert.SerializeObject(data);
db.StringSet(key, str, TimeSpan.FromMinutes(cacheTime));
}
public void Set(string key, object data)
{
var db = RedisManager.Manager.GetDatabase();
string str = JsonConvert.SerializeObject(data);
db.StringSet(key, str);
}
public bool IsSet(string key)
{
var db = RedisManager.Manager.GetDatabase();
return db.KeyExists(key);
}
public void Remove(string key)
{
var db = RedisManager.Manager.GetDatabase();
db.KeyDelete(key);
}