using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Configuration;
using Newtonsoft.Json;
namespace Services
{
public class CacheService
{
private static CacheService instance = new CacheService();
private static Logger logger = LogManager.GetCurrentClassLogger();
int Default_Timeout = ;//默认超时时间(单位秒)
ConnectionMultiplexer redisConnection;
IDatabase cache;
/// <summary>
/// 连接超时设置
/// </summary>
public int TimeOut
{
get
{
return Default_Timeout;
}
set
{
Default_Timeout = value;
}
}
/// <summary>
/// 构造函数
/// </summary>
private CacheService()
{
//redisConnection = ConnectionMultiplexer.Connect(ConfigurationManager.ConnectionStrings["RedisConnection"].ConnectionString);
redisConnection = ConnectionMultiplexer.Connect(AppConfig.connectClientRedis);
#region 注册事件
//注册如下事件
redisConnection.ConnectionFailed += MuxerConnectionFailed;
redisConnection.ConnectionRestored += MuxerConnectionRestored;
redisConnection.ErrorMessage += MuxerErrorMessage;
redisConnection.ConfigurationChanged += MuxerConfigurationChanged;
redisConnection.HashSlotMoved += MuxerHashSlotMoved;
redisConnection.InternalError += MuxerInternalError;
#endregion
cache = redisConnection.GetDatabase();
}
/// <summary>
/// 实例化
/// </summary>
/// <returns></returns>
public static CacheService GetInstance()
{
return instance;
}
/// <summary>
/// 保存一个对象
/// </summary>
/// <typeparam name="T">泛型对象</typeparam>
/// <param name="key">key</param>
/// <param name="obj">对象</param>
/// <returns></returns>
public bool Set<T>(string key, T obj)
{
try
{
// var timeSpan = TimeSpan.FromSeconds(TimeOut);
var json = ConvertJson(obj);
return cache.StringSet(key, json);
}
catch (Exception ex)
{
logger.Error("=========== Class:CacheService method:Set ===========");
logger.Error("=========== Key:" + key + " value:" + ConvertJson(obj) + "===========");
logger.Error(ex);
}
return false;
}
/// <summary>
/// 获取一个key的对象
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <returns></returns>
public T Get<T>(string key)
{
RedisValue values = cache.StringGet(key);
return ConvertObj<T>(values);
}
public void Batch(IEnumerable<KeyValuePair<string, string>> keyValuePairs)
{
var batch = cache.CreateBatch();
foreach (var k in keyValuePairs)
{
//var json = ConvertJson(k.Value);
batch.StringSetAsync(k.Key, k.Value);
//batch.SetAddAsync(k.Key, k.Value);
}
batch.Execute();
}
#region JSON,T 相互转换
private string ConvertJson<T>(T value)
{
string result = value is string ? value.ToString() : JsonConvert.SerializeObject(value);
return result;
}
private T ConvertObj<T>(RedisValue value)
{
if (value.IsNull)
{
return default(T);
}
return JsonConvert.DeserializeObject<T>(value);
}
#endregion
#region 事件
/// <summary>
/// 配置更改时
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private static void MuxerConfigurationChanged(object sender, EndPointEventArgs e)
{
logger.Info("Configuration changed: " + e.EndPoint);
}
/// <summary>
/// 发生错误时
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private static void MuxerErrorMessage(object sender, RedisErrorEventArgs e)
{
logger.Error("ErrorMessage: " + e.Message);
}
/// <summary>
/// 重新建立连接之前的错误
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private static void MuxerConnectionRestored(object sender, ConnectionFailedEventArgs e)
{
logger.Error("ConnectionRestored: " + e.EndPoint);
}
/// <summary>
/// 连接失败 , 如果重新连接成功你将不会收到这个通知
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private static void MuxerConnectionFailed(object sender, ConnectionFailedEventArgs e)
{
logger.Error("重新连接:Endpoint failed: " + e.EndPoint + ", " + e.FailureType + (e.Exception == null ? "" : (", " + e.Exception.Message)));
}
/// <summary>
/// 更改集群
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private static void MuxerHashSlotMoved(object sender, HashSlotMovedEventArgs e)
{
logger.Info("HashSlotMoved:NewEndPoint" + e.NewEndPoint + ", OldEndPoint" + e.OldEndPoint);
}
/// <summary>
/// redis类库错误
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private static void MuxerInternalError(object sender, InternalErrorEventArgs e)
{
logger.Error("InternalError:Message" + e.Exception.Message);
}
#endregion 事件
}
}