using Common;
using System;
using System.Collections.Generic;
namespace KC.Cache.Redis
{
///
/// 对外接口
///
public class RedisCache : ICache
{
private static RedisHelper redisHelper = new RedisHelper();
private static RedisCache _redisCache = new RedisCache();
private static int timeOut = ConfigHelper.GetValue("RedisTimeOut").TryToInt32();
public static RedisCache GetRedisCache()
{
return _redisCache;
}
///
/// 写入缓存,单体
///
/// 对象数据
/// 键
/// 几秒过期
public void WriteCache(string cacheKey, T value, int seconds = 0) where T : class
{
TimeSpan span = DateTime.Now.AddSeconds((seconds == 0 ? timeOut : seconds)) - DateTime.Now;
redisHelper.KeyDelete(cacheKey);
Type type = typeof(T);
if (type == typeof(string))
{
lock (redisHelper)
{
redisHelper.StringSet(cacheKey, value, span);
}
}
else if (type == typeof(T))
{
lock (redisHelper)
{
redisHelper.ListSet(cacheKey, value);
}
redisHelper.KeyExpire(cacheKey, span);
}
}
///
/// 写入缓存,字符串
///
/// 对象数据
/// 键
/// 到期时间
public void WriteStringCache(string value, string cacheKey,int seconds=0)
{
redisHelper.KeyDelete(cacheKey);
lock (redisHelper)
{
redisHelper.StringSet(cacheKey, value.ToString(), DateTime.Now.AddSeconds((seconds==0? timeOut : seconds)) - DateTime.Now);
}
}
///
/// 写入缓存,集合
///
/// 对象数据
/// 键
/// 到期时间
public void WriteListCache(string cacheKey, List value, int seconds = 0) where T : class
{
redisHelper.KeyDelete(cacheKey);
TimeSpan span = DateTime.Now.AddSeconds((seconds == 0 ? timeOut : seconds)) - DateTime.Now;
if (value.Count <= 0)
return;
redisHelper.ListSet>(cacheKey, value);
redisHelper.KeyExpire(cacheKey, span);
}
///
/// 读取缓存,单体
///
/// 键
///
public T GetCache(string cacheKey) where T : class
{
Type type = typeof(T);
T res = null;
if (type == typeof(string))
{
res = redisHelper.StringGet(cacheKey) as T;
}
else if (type == typeof(T))
{
res = redisHelper.ListRangeObj(cacheKey) as T;
}
return res;
}
///
/// 读取缓存,字符串
///
/// 键
///
public string GetStringCache(string cacheKey)
{
return redisHelper.StringGet(cacheKey);
}
///
/// 读取缓存,集合
///
/// 键
///
public List GetListCache(string cacheKey) where T : class
{
var res = redisHelper.ListGet(cacheKey) as List;
return res;
}
///
/// 获取所有key
///
///
public List GetAllKeys()
{
return redisHelper.GetAllKeys();
}
///
/// 确定当前Key是否过期
///
///
///
public bool HasExpire(string key)
{
return redisHelper.KeyExists(key);
}
///
/// 移除指定数据缓存
///
/// 键
public void RemoveCache(string key)
{
redisHelper.KeyDelete(key);
}
///
/// 批量删除数据缓存
///
///
public void RemoveCache(List keys)
{
redisHelper.KeyDelete(keys);
}
}
}