using System; using System.Collections.Generic; using System.Linq; using System.Text; using ServiceStack.Redis; namespace ZhengXin.Tools { public class RedisUtils { /// <summary> /// 默认过期时间 为秒 /// </summary> private static int secondsTimeOut = 30 * 60; #region @Royal改进部分,能操作16个库 private static readonly Dictionary<int, PooledRedisClientManager> pools = new Dictionary<int, PooledRedisClientManager>(); static RedisUtils() { string path = ConfigHelper.GetConfigKeyValue("RedisPath"); string[] readWriteHosts = new string[] { path }; string[] readOnlyHosts = new string[] { path };
//初始化16个缓存库 for (int i = 0; i <= 15; i++) { var model = new PooledRedisClientManager(readWriteHosts, readOnlyHosts, new RedisClientManagerConfig { MaxWritePoolSize = 50, // “写”链接池链接数 MaxReadPoolSize = 50, // “读”链接池链接数 AutoStart = true, }, i, 100, 20); pools.Add(i, model); } } public static PooledRedisClientManager ChooseRedisInstance(int database) { if (database > 16) return pools[0]; return pools[database]; } public static void Lpush(string key, string value, int database = 0) { using (IRedisClient redis = ChooseRedisInstance(database).GetClient()) { redis.PushItemToList(key, value); } } public static string Lpop(string key, int database = 0) { using (IRedisClient redis = ChooseRedisInstance(database).GetClient()) { return redis.PopItemFromList(key); } } public static List<string> List(string key, int database = 0) { using (IRedisClient redis = ChooseRedisInstance(database).GetClient()) { return redis.GetAllItemsFromList(key); } } public static bool ItemSet<T>(string key, T t, int timeout = 0, int db = 2) { using (IRedisClient RClient = ChooseRedisInstance(db).GetClient()) { if (timeout >= 0) { if (timeout > 0) { secondsTimeOut = timeout; } } return RClient.Add<T>(key, t, TimeSpan.FromMinutes(secondsTimeOut)); } } public static T ItemGet<T>(string key, int db = 2) where T : class { using (IRedisClient redis = ChooseRedisInstance(db).GetClient()) { return redis.Get<T>(key); } } } }
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:自己封装的C#操作redis公共类 - Python技术站