ServiceStack.Redis操作Redis配置单例模式
电脑版发表于:2018/12/21 10:09
我携漫天星辰以赠你,仍觉漫天星辰不如你。
单利的应该是连接池而不应该是redis对象。如果每次操作都是一个redis对象是会有并发问题的,
应该从连接池中去拿。
解释半天都没有用直接贴代码吧
public class SingletonRedis { // 定义一个静态变量来保存类的实例 private static PooledRedisClientManager poolrl; private static readonly object obj = new object(); // 定义私有构造函数,使外界不能创建该类实例 private SingletonRedis() { } /// <summary> /// 获取Redis写节点 /// </summary> /// <returns></returns> public static RedisClient GetInstance() { // 如果连接池的实例不存在则创建,否则直接返回 if (poolrl == null) { lock (obj) { if (poolrl == null) { CreatePoolManager(); } } } return poolrl.GetClient() as RedisClient; } /// <summary> /// 获取Redis读节点 /// </summary> /// <returns></returns> public static RedisClient GetReadOnlyInstance() { if (poolrl == null) { lock (obj) { if (poolrl == null) { CreatePoolManager(); } } } return poolrl.GetReadOnlyClient() as RedisClient; } private static void CreatePoolManager() { //----------------------发布的时候用外网--------------------------- //----------------------测试的时候用本地--------------------------- //写节点(主节点) List<string> writes = new List<string>(); writes.Add("127.0.0.1:6379"); //读节点 List<string> reads = new List<string>(); reads.Add("127.0.0.1:6379"); //配置连接池和读写分类 poolrl = new PooledRedisClientManager(writes, reads, new RedisClientManagerConfig() { MaxReadPoolSize = 50, //读节点个数 MaxWritePoolSize = 50,//写节点个数 }); } }