using Admin.Core.Common;
using StackExchange.Redis;
using System;
namespace Admin.Core.Extensions
{
public class RedisCacheManager : IRedisCacheManager
{
private readonly string redisConnenctionString;
public volatile ConnectionMultiplexer redisConnection;
private readonly object redisConnectionLock = new object();
public RedisCacheManager()
{
string redisConfiguration = Appsettings.app(new string[] { "AppSettings", "RedisCachingAOP", "ConnectionString" });//获取连接字符串
if (string.IsNullOrWhiteSpace(redisConfiguration))
{
throw new ArgumentException("redis config is empty", nameof(redisConfiguration));
}
this.redisConnenctionString = redisConfiguration;
this.redisConnection = GetRedisConnection();
}
///
/// 核心代码,获取连接实例
/// 通过双if 加lock的方式,实现单例模式
///
///
private ConnectionMultiplexer GetRedisConnection()
{
//如果已经连接实例,直接返回
if (this.redisConnection != null && this.redisConnection.IsConnected)
{
return this.redisConnection;
}
//加锁,防止异步编程中,出现单例无效的问题
lock (redisConnectionLock)
{
if (this.redisConnection != null)
{
//释放redis连接
this.redisConnection.Dispose();
}
try
{
var config = new ConfigurationOptions
{
AbortOnConnectFail = false,
AllowAdmin = true,
ConnectTimeout = 15000,//改成15s
SyncTimeout = 5000,
//Password = "Pwd",//Redis数据库密码
EndPoints = { redisConnenctionString }// connectionString 为IP:Port 如”192.168.2.110:6379”
};
this.redisConnection = ConnectionMultiplexer.Connect(config);
}
catch (Exception)
{
throw new Exception("Redis服务未启用,请开启该服务,并且请注意端口号,本项目使用的的6319,而且我的是没有设置密码。");
}
}
return this.redisConnection;
}
///
/// 清除
///
public void Clear()
{
foreach (var endPoint in this.GetRedisConnection().GetEndPoints())
{
var server = this.GetRedisConnection().GetServer(endPoint);
foreach (var key in server.Keys())
{
redisConnection.GetDatabase().KeyDelete(key);
}
}
}
///
/// 判断是否存在
///
///
///
public bool Get(string key)
{
return redisConnection.GetDatabase().KeyExists(key);
}
///
/// 查询
///
///
///
public string GetValue(string key)
{
return redisConnection.GetDatabase().StringGet(key);
}
///
/// 获取
///
///
///
///
public TEntity Get(string key)
{
var value = redisConnection.GetDatabase().StringGet(key);
if (value.HasValue)
{
//需要用的反序列化,将Redis存储的Byte[],进行反序列化
return SerializeHelper.Deserialize(value);
}
else
{
return default(TEntity);
}
}
///
/// 移除
///
///
public void Remove(string key)
{
redisConnection.GetDatabase().KeyDelete(key);
}
///
/// 设置
///
///
///
///
public void Set(string key, object value, TimeSpan cacheTime)
{
if (value != null)
{
//序列化,将object值生成RedisValue
redisConnection.GetDatabase().StringSet(key, SerializeHelper.Serialize(value), cacheTime);
}
}
///
/// 增加/修改
///
///
///
///
public bool SetValue(string key, byte[] value)
{
return redisConnection.GetDatabase().StringSet(key, value, TimeSpan.FromSeconds(120));
}
}
}