|
public class RedisHelper : IDisposable
{
private static string strRedis = System.Configuration.ConfigurationManager.AppSettings["RedisPath"].ToString();//web.config中配置我本机的一个IP
public RedisClient Redis = new RedisClient(strRedis, 6379);
//缓存池
PooledRedisClientManager prcm = new PooledRedisClientManager();
//默认缓存过期时间单位秒
public int secondsTimeOut = 30 * 60;
///
/// 缓冲池
///
///
///
///
public static PooledRedisClientManager CreateManager(
string[] readWriteHosts, string[] readOnlyHosts)
{
return new PooledRedisClientManager(readWriteHosts, readOnlyHosts,
new RedisClientManagerConfig
{
MaxWritePoolSize = readWriteHosts.Length * 5,
MaxReadPoolSize = readOnlyHosts.Length * 5,
AutoStart = true,
});
}
///
/// 构造函数
///
/// 是否开启缓冲池
public RedisHelper(bool OpenPooledRedis = false)
{
if (OpenPooledRedis)
{
prcm = CreateManager(new string[] { strRedis + ":6379" }, new string[] { strRedis + ":6379" });
Redis = prcm.GetClient() as RedisClient;
}
}
#region Key/Value存储
///
/// 设置缓存
///
///
/// 缓存建
/// 缓存值
/// 过期时间,单位秒,-1:不过期,0:默认过期时间
///
public bool Set(string key, T t, int timeout = 0)
{
if (timeout >= 0)
{
if (timeout > 0)
{
secondsTimeOut = timeout;
}
Redis.Expire(key, secondsTimeOut);
}
return Redis.Add(key, t);
}
///
/// 获取(根据key来获取value)
///
///
///
///
public T Get(string key)
{
return Redis.Get(key);
}
///
/// 移除整个类型的key
///
///
///
public bool Remove(string key)
{
return Redis.Remove(key);
}
///
/// key是否存在(0:不存在;1;存在)
///
///
///
public int IsExists(string key)
{
return Convert.ToInt32(Redis.Exists(key));
}
public bool Add(string key, T t, int timeout)
{
if (timeout >= 0)
{
if (timeout > 0)
{
secondsTimeOut = timeout;
}
Redis.Expire(key, secondsTimeOut);
}
return Redis.Add(key, t);
}
#endregion
///
/// 释放资源
///
public void Dispose()
{
if (Redis != null)
{
Redis.Dispose();
Redis = null;
}
GC.Collect();
}
#region Hash的方法
///
/// 判断某个数据是否已经被缓存
///
public bool Exist(string hashId, string key)
{
return Redis.HashContainsEntry(hashId, key);
}
///
/// 存储数据到hash表
///
public bool Set1(string hashId, string key, string value)
{
return Redis.SetEntryInHash(hashId, key, value);
}
///
/// 移除hash中的某值
///
public bool Remove(string hashId, string key)
{
return Redis.RemoveEntryFromHash(hashId, key);
}
///
/// 从hash表获取数据
///
public string Get1(string hashId, string key)
{
return Redis.GetValueFromHash(hashId, key);
}
///
/// 获取整个hash的数据
///
public string GetAll1(string hashId)
{
string result = "";
var list = Redis.GetHashValues(hashId);
if (list != null && list.Count > 0)
{
for (int i = 0; i < list.Count; i++)
{
var aa = list;
result += aa + ",";
}
result = result.Trim(',');
}
return result;
}
///
/// 设置缓存过期
///
public void SetExpire(string key, DateTime datetime)
{
Redis.ExpireEntryAt(key, datetime);
}
#endregion
}
|
|
|