net core使用servicestack.redis连接redis,读写分离
电脑版发表于:2019/12/2 12:04
servicestack.redis5.7版本开始支持net core 3.x
官网地址:https://servicestack.net/redis
下载:
Install-Package ServiceStack.Redis
或者:
<ItemGroup> <PackageReference Include="ServiceStack.Redis" Version="5.7.0" /> </ItemGroup>
读写分离类:
用于获取实例
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 = 66, //读节点个数 MaxWritePoolSize = 50,//写节点个数 }); } }
简单示例:
代码如下:
public class ConfigRedis : IConfigRedis { public string QueryConfigByKey(string key) { using (RedisClient redis = SingletonRedis.GetReadOnlyInstance()) { string value = redis.Get<string>(key); return value; } } public void AddConfig(string key, string value) { using (RedisClient redis = SingletonRedis.GetInstance()) { redis.Add<string>(key, value); } } }