using ERP.Framework.Config;
using StackExchange.Redis;
using System.Diagnostics.CodeAnalysis;
namespace ERP.Framework.Cache
{
public static class RedisHelper
{
[NotNull]
private static IDatabase? DB { get; set; }
private static IConnectionMultiplexer? _connMultiplexer;
private static readonly object _lock = new object();
public static void Init(RedisConfig redisConfig)
{
try
{
var redisConnectionStr = $"{redisConfig.Host}:{redisConfig.Port}";
var options = ConfigurationOptions.Parse(redisConnectionStr);
options.Password = redisConfig.Password;
var connectionMultiplexer = GetConnectRedisMultiplexer(options);
DB = connectionMultiplexer.GetDatabase();
}
catch (Exception err)
{
// Todo Redis初始化异常
}
}
private static IConnectionMultiplexer GetConnectRedisMultiplexer(ConfigurationOptions options)
{
if (_connMultiplexer == null)
{
lock (_lock)
{
if (_connMultiplexer != null)
{
return _connMultiplexer;
}
_connMultiplexer = ConnectionMultiplexer.Connect(options);
//Todo 注册事件
//_connMultiplexer.ConnectionFailed
//_connMultiplexer.ConnectionFailed += MuxerConnectionFailed;
//_connMultiplexer.ConnectionRestored += MuxerConnectionRestored;
//_connMultiplexer.ErrorMessage += MuxerErrorMessage;
//_connMultiplexer.ConfigurationChanged += MuxerConfigurationChanged;
//_connMultiplexer.HashSlotMoved += MuxerHashSlotMoved;
//_connMultiplexer.InternalError += MuxerInternalError;
}
}
return _connMultiplexer;
}
#region Event
///
/// 添加注册事件
///
private static void AddRegisterEvent()
{
//_connMultiplexer.ConnectionRestored += ConnMultiplexer_ConnectionRestored;
//_connMultiplexer.ConnectionFailed += ConnMultiplexer_ConnectionFailed;
//_connMultiplexer.ErrorMessage += ConnMultiplexer_ErrorMessage;
//_connMultiplexer.ConfigurationChanged += ConnMultiplexer_ConfigurationChanged;
//_connMultiplexer.HashSlotMoved += ConnMultiplexer_HashSlotMoved;
//_connMultiplexer.InternalError += ConnMultiplexer_InternalError;
//_connMultiplexer.ConfigurationChangedBroadcast += ConnMultiplexer_ConfigurationChangedBroadcast;
}
/////
///// 重新配置广播时(通常意味着主从同步更改)
/////
/////
/////
//private static void ConnMultiplexer_ConfigurationChangedBroadcast(object sender, EndPointEventArgs e)
//{
//}
/////
///// 发生内部错误时(主要用于调试)
/////
/////
/////
//private static void ConnMultiplexer_InternalError(object sender, InternalErrorEventArgs e)
//{
//}
/////
///// 更改集群时
/////
/////
/////
//private static void ConnMultiplexer_HashSlotMoved(object sender, HashSlotMovedEventArgs e)
//{
//}
/////
///// 配置更改时
/////
/////
/////
//private static void ConnMultiplexer_ConfigurationChanged(object sender, EndPointEventArgs e)
//{
//}
/////
///// 发生错误时
/////
/////
/////
//private static void ConnMultiplexer_ErrorMessage(object sender, RedisErrorEventArgs e)
//{
//}
/////
///// 物理连接失败时
/////
/////
/////
//private static void ConnMultiplexer_ConnectionFailed(object sender, ConnectionFailedEventArgs e)
//{
//}
/////
///// 建立物理连接时
/////
/////
/////
//private static void ConnMultiplexer_ConnectionRestored(object sender, ConnectionFailedEventArgs e)
//{
//}
#endregion Event
#region String
///
/// set or update the value for string key
///
///
///
///
public static bool Save(string key, string value)
{
return DB.StringSet(key, value);
}
///
/// set or update the value for string key
///
///
///
///
public static bool SaveExpire(string key, string value, TimeSpan? expireMinutes)
{
return DB.StringSet(key, value, expireMinutes);
}
///
/// set or update the value for string key
///
///
///
///
public static bool SaveExpire(string key, string value, int expireMinutes)
{
return DB.StringSet(key, value, TimeSpan.FromMinutes(expireMinutes));
}
///
/// get the value for string key
///
///
///
public static string Get(string key)
{
return DB.StringGet(key);
}
///
/// get the value for string key
///
///
///
public static RedisValueWithExpiry GetWithExpire(string key)
{
return DB.StringGetWithExpiry(key);
}
///
/// Delete the value for string key
///
///
///
public static bool Delete(string key)
{
return DB.KeyDelete(key);
}
#endregion String
/////
///// 新增Redis值(有时限)
/////
///// id
///// 值
///// 时限(分钟,默认30天)
/////
//public static bool AddExpire(string key, string value, int expireMinutes = 24 * 60 * 30)
// => new RedisHelper().AddExpireValue(key, value, expireMinutes);
/////
///// 保存一个对象
/////
/////
/////
/////
/////
//public bool SetStringKey(string key, T obj, int expireMinutes = 0)
//{
// string json = JsonConvert.SerializeObject(obj);
// if (expireMinutes > 0)
// {
// return DB.StringSet(key, json, TimeSpan.FromMinutes(expireMinutes));
// }
// else
// return DB.StringSet(key, json);
//}
/////
///// 获取一个key的对象
/////
/////
/////
/////
//public T GetStringKey(string key) where T : class
//{
// var result = DB.StringGet(key);
// if (string.IsNullOrEmpty(result))
// {
// return null;
// }
// try
// {
// return JsonConvert.DeserializeObject(result);
// }
// catch
// {
// return null;
// }
//}
/////
///// set or update the HashValue for string key
/////
/////
/////
/////
/////
//public bool SetHashValue(string key, string hashkey, string value)
//{
// return DB.HashSet(key, hashkey, value);
//}
/////
///// set or update the HashValue for string key
/////
/////
/////
/////
///// defined class
/////
//public bool SetHashValue(String key, string hashkey, T t) where T : class
//{
// var json = JsonConvert.SerializeObject(t);
// return DB.HashSet(key, hashkey, json);
//}
//public static void HashSet(string key, List list, Func getModelId)
// => new RedisHelper().HashSetValue(key, list, getModelId);
//public static void HashSetExpire(string key, List list, Func getModelId, int expireTime = 24 * 60 * 30)
//=> new RedisHelper().HashSetExpireValue(key, list, getModelId, expireTime);
/////
///// 保存一个集合
/////
/////
///// Redis Key
///// 数据集合
/////
//public void HashSetValue(string key, List list, Func getModelId)
//{
// List listHashEntry = new List();
// foreach (var item in list)
// {
// string json = JsonConvert.SerializeObject(item);
// listHashEntry.Add(new HashEntry(getModelId(item), json));
// }
// DB.HashSet(key, listHashEntry.ToArray());
//}
/////
///// 保存一个集合
/////
/////
///// Redis Key
///// 数据集合
/////
//private void HashSetExpireValue(string key, List list, Func getModelId, int expireTime)
//{
// List listHashEntry = new List();
// foreach (var item in list)
// {
// string json = JsonConvert.SerializeObject(item);
// listHashEntry.Add(new HashEntry(getModelId(item), json));
// }
// DB.HashSet(key, listHashEntry.ToArray());
// DB.KeyExpire(key, TimeSpan.FromMinutes(expireTime));
//}
/////
///// 获取hashkey所有的值
/////
/////
/////
/////
//public List HashGetAll(string key) where T : class
//{
// List result = new List();
// HashEntry[] arr = DB.HashGetAll(key);
// foreach (var item in arr)
// {
// if (!item.Value.IsNullOrEmpty)
// {
// result.Add(Newtonsoft.Json.JsonConvert.DeserializeObject(item.Value));
// }
// }
// return result;
//}
/////
///// get the HashValue for string key and hashkey
/////
///// Represents a key that can be stored in redis
/////
/////
//public RedisValue GetHashValue(string key, string hashkey)
//{
// RedisValue result = DB.HashGet(key, hashkey);
// return result;
//}
/////
///// get the HashValue for string key and hashkey
/////
///// Represents a key that can be stored in redis
/////
/////
//public T GetHashValue(string key, string hashkey) where T : class
//{
// RedisValue result = DB.HashGet(key, hashkey);
// if (string.IsNullOrEmpty(result))
// {
// return null;
// }
// T t = JsonConvert.DeserializeObject(result);
// return null;
//}
/////
///// delete the HashValue for string key and hashkey
/////
/////
/////
/////
//public bool DeleteHashValue(string key, string hashkey)
//{
// return DB.HashDelete(key, hashkey);
//}
}
}