public class RedisCacheImp
{
private IDatabase cache;
private ConnectionMultiplexer connection;
public RedisCacheImp()
{
connection = ConnectionMultiplexer.Connect("127.0.0.1:6379");
cache = connection.GetDatabase();
}
public bool SetCache<T>(string key, T value, DateTime? expireTime = null)
{
try
{
var jsonOption = new JsonSerializerSettings()
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
};
string strValue = JsonConvert.SerializeObject(value, jsonOption);
if (string.IsNullOrEmpty(strValue))
{
return false;
}
if (expireTime == null)
{
return cache.StringSet(key, strValue);
}
else
{
return cache.StringSet(key, strValue, (expireTime.Value - DateTime.Now));
}
}
catch (Exception ex)
{
}
return false;
}
public bool RemoveCache(string key)
{
return cache.KeyDelete(key);
}
public T GetCache<T>(string key)
{
var t = default(T);
try
{
var value = cache.StringGet(key);
if (string.IsNullOrEmpty(value))
{
return t;
}
t = JsonConvert.DeserializeObject<T>(value);
}
catch (Exception ex)
{
}
return t;
}
}
Redis类
猜你喜欢
转载自blog.csdn.net/varcad/article/details/113887540
今日推荐
周排行