C#连接Redis-使用 ServiceStack.Redis 自由切换db
前段时间用Redis优化了公司的一个c#项目模块,刚上线时表现还是不错的,但后来发现不太对劲。高峰期时CPU占比很高,于是想找优化方案。
RedisClient RedisClient = new RedisClient("127.0.0.1", 6379);
以上是我一开始采用的链接方式,这种方式会在高峰期时频繁创建和释放链接,对CPU的消耗很大。于是经过一番搜寻,改用了连接池的方式。使用PooledRedisClientManager连接缓冲池中获取连接,使用完毕后还给连接池。
namespace Web { /// <summary> /// Redis客户端管理类 /// </summary> public static class RedisManager { private static PooledRedisClientManager clientManager; /// <summary> /// 初始化信息 /// </summary> private static void initInfo() { string host = string.Format("{0}:{1}", "127.0.0.1", "6379"); //这里的IP和端口号大多数人写在配置文件里,我这里因为小功能模块,自己用就直接写在代码里了 initInfo(new string[] { host},new string[] { host}); } /// <summary> /// 初始化Redis客户端管理 /// </summary> /// <param name="readWriteHosts"></param> /// <param name="readOnlyHosts"></param> private static void initInfo(string[] readWriteHosts, string[] readOnlyHosts) { clientManager = new PooledRedisClientManager(readWriteHosts, readOnlyHosts, new RedisClientManagerConfig { MaxWritePoolSize = 200, //写链接池链接数 MaxReadPoolSize = 50, //读链接池链接数 AutoStart = true }); } public static IRedisClient getRedisClient() { if (clientManager == null) { initInfo(); } return clientManager.GetClient(); } } }
下面是调用方法,当然你也可以使用using
namespace Web { public class RedisHelper { public static string getList(string DeviceName,int num) { try { RedisClient redisClient = (RedisClient)RedisManager.getRedisClient(); redisClient.ChangeDb(num); string res = redisClient.GetValue(DeviceName) ?? "[]"; redisClient.Dispose(); return res; } catch { return "[]"; //return e.Message; } } public static int setList(string DeviceName, string list, int num) { try { RedisClient redisClient = (RedisClient)RedisManager.getRedisClient(); redisClient.ChangeDb(num); redisClient.SetEntry(DeviceName,list); redisClient.Dispose(); } catch { return 0; } return 1; } } }