using System; using System.Collections.Generic; using System.Linq; using System.Text; using ServiceStack.Redis; using ServiceStack.Redis.Generic; using ServiceStack.Text; using ServiceStack.Redis.Support; namespace OSS.ETS.OMS.Common { public class RedisCache : ICache { private static PooledRedisClientManager prcm = RedisCache.CreateRedisManager(new string[] { System.Configuration.ConfigurationManager.AppSettings["RedisHosts"] }, new string[] { System.Configuration.ConfigurationManager.AppSettings["RedisHosts"] }); /// <summary> /// 创建Redis连接池管理对象 /// </summary> public static PooledRedisClientManager CreateRedisManager(string[] readWriteHosts, string[] readOnlyHosts) { //支持读写分离,均衡负载 return new PooledRedisClientManager(readWriteHosts, readOnlyHosts, new RedisClientManagerConfig { MaxWritePoolSize = 5, //“写”链接池数 MaxReadPoolSize = 5, //“读”链接池数 AutoStart = true, }); } /// <summary> /// 添加数据 /// </summary> public void Set<T>(string key, T val) { using (IRedisClient rds = prcm.GetClient()) { rds.Set<T>(key, val); } } /// <summary> /// 读取数据 /// </summary> public T Get<T>(string key) where T : class { using (IRedisClient rds = prcm.GetReadOnlyClient()) { return rds.Get<T>(key); } } /// <summary> /// 删除数据 /// </summary> public void Remove(string key) { using (IRedisClient rds = prcm.GetClient()) { rds.Remove(key); } } public void Add(string key, object value) { using (IRedisClient rds = prcm.GetClient()) { if (!rds.ContainsKey(key)) rds.Add(key, value, DateTime.Now.AddMinutes(30)); else rds.Set(key, value); rds.Set(key, value, DateTime.Now.AddMinutes(30)); } } /// <summary> /// 刷新缓存 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="key"></param> public void RefreshCache<T>(string key) where T : class { using (IRedisClient rds = prcm.GetClient()) { T value = rds.Get<T>(key); rds.Remove(key); rds.Set<T>(key, value); } } public bool ContainsKey(string key) { using (IRedisClient rds = prcm.GetReadOnlyClient()) { return rds.ContainsKey(key); } } } } |
|