一.添加引用包
StackExchange.Redis
Microsoft.Extensions.Configuration
二.修改配置文件 appsettings.json
{ "RedisConfig": { "Redis_Default": { "Connection": "127.0.0.1: 6379", "InstanceName": "Redis1: " }, "Redis_6": { "Connection": "127.0.0.1: 6379", "DefaultDatabase": 6, "InstanceName": "Redis2: " } } }
三.简单封装
RedisClient.cs类
1 public class RedisClient : IDisposable 2 { 3 private IConfigurationRoot _config; 4 private ConcurrentDictionary<string, ConnectionMultiplexer> _connections; 5 public RedisClient(IConfigurationRoot config) 6 { 7 _config = config; 8 _connections = new ConcurrentDictionary<string, ConnectionMultiplexer>(); 9 } 10 /// <summary> 11 /// 获取ConnectionMultiplexer 12 /// </summary> 13 /// <param name="redisConfig">RedisConfig配置文件</param> 14 /// <returns></returns> 15 private ConnectionMultiplexer GetConnect(IConfigurationSection redisConfig) 16 { 17 var redisInstanceName = redisConfig["InstanceName"]; 18 var connStr = redisConfig["Connection"]; 19 return _connections.GetOrAdd(redisInstanceName, p => ConnectionMultiplexer.Connect(connStr)); 20 } 21 /// <summary> 22 /// 检查入参数 23 /// </summary> 24 /// <param name="configName">RedisConfig配置文件中的 Redis_Default/Redis_6 名称</param> 25 /// <returns></returns> 26 private IConfigurationSection CheckeConfig(string configName) 27 { 28 IConfigurationSection redisConfig = _config.GetSection("RedisConfig").GetSection(configName); 29 if (redisConfig == null) 30 { 31 throw new ArgumentNullException($"{configName}找不到对应的RedisConfig配置!"); 32 } 33 var redisInstanceName = redisConfig["InstanceName"]; 34 var connStr = redisConfig["Connection"]; 35 if (string.IsNullOrEmpty(redisInstanceName)) 36 { 37 throw new ArgumentNullException($"{configName}找不到对应的InstanceName"); 38 } 39 if (string.IsNullOrEmpty(connStr)) 40 { 41 throw new ArgumentNullException($"{configName}找不到对应的Connection"); 42 } 43 return redisConfig; 44 } 45 /// <summary> 46 /// 获取数据库 47 /// </summary> 48 /// <param name="configName"></param> 49 /// <param name="db">默认为0:优先代码的db配置,其次config中的配置</param> 50 /// <returns></returns> 51 public IDatabase GetDatabase(string configName = null, int? db = null) 52 { 53 int defaultDb = 0; 54 IConfigurationSection redisConfig = CheckeConfig(configName); 55 if (db.HasValue) 56 { 57 defaultDb = db.Value; 58 } 59 else 60 { 61 var strDefalutDatabase = redisConfig["DefaultDatabase"]; 62 if (!string.IsNullOrEmpty(strDefalutDatabase) && Int32.TryParse(strDefalutDatabase, out var intDefaultDatabase)) 63 { 64 defaultDb = intDefaultDatabase; 65 } 66 } 67 return GetConnect(redisConfig).GetDatabase(defaultDb); 68 } 69 70 public IServer GetServer(string configName = null, int endPointsIndex = 0) 71 { 72 IConfigurationSection redisConfig = CheckeConfig(configName); 73 var connStr = redisConfig["Connection"]; 74 75 var confOption = ConfigurationOptions.Parse((string)connStr); 76 return GetConnect(redisConfig).GetServer(confOption.EndPoints[endPointsIndex]); 77 } 78 79 public ISubscriber GetSubscriber(string configName = null) 80 { 81 IConfigurationSection redisConfig = CheckeConfig(configName); 82 return GetConnect(redisConfig).GetSubscriber(); 83 } 84 85 public void Dispose() 86 { 87 if (_connections != null && _connections.Count > 0) 88 { 89 foreach (var item in _connections.Values) 90 { 91 item.Close(); 92 } 93 } 94 } 95 }
因为RedisClient 中使用了ConcurrentDictionary
所以,有了RedisClientSingleton.cs类
1 public class RedisClientSingleton 2 { 3 private static RedisClient _redisClinet; 4 private RedisClientSingleton() { } 5 6 private static object _lockObj = new object(); 7 public static RedisClient GetInstance(IConfigurationRoot config) 8 { 9 if (_redisClinet == null) 10 { 11 lock (_lockObj) 12 { 13 if (_redisClinet == null) 14 { 15 _redisClinet = new RedisClient(config); 16 } 17 } 18 } 19 return _redisClinet; 20 } 21 }
四.测试
1、控制台程序
1)创建一个Controller程序
2)添加引用包
Microsoft.Extensions.Configuration
Microsoft.Extensions.Configuration.Json
3)添加appsettings.json
添加以下
"RedisConfig": { "Redis_Default": { "Connection": "127.0.0.1:6379", "InstanceName": "Redis1:" }, "Redis_6": { "Connection": "127.0.0.1:6379", "DefaultDatabase": 6, "InstanceName": "Redis2:" } }
4)修改Program类
①添加引用using Microsoft.Extensions.Configuration;
②修改Main
1 static void Main(string[] args) 2 { 3 var builder = new ConfigurationBuilder()
4 .SetBasePath(Directory.GetCurrentDirectory()) 5 .AddJsonFile("appsettings.json"); 6 IConfigurationRoot configuration = builder.Build(); 7 8 var redisClient = RedisClientSingleton.GetInstance(configuration); 9 var redisDatabase = redisClient.GetDatabase("Redis_Default"); 10 11 redisDatabase.StringSet("TestStrKey", "TestStrValue"); 12 }
③运行后可以看到
2、web程序
①创建一个core的mvc项目
②修改Startup.cs文件
修改ConfigureServices函数
public void ConfigureServices(IServiceCollection services) { ... services.AddSingleton(Configuration); ... }
其中的Configuration是 public IConfigurationRoot Configuration { get; }
③创建一个TestController
在修改构造函数
SimpleRedisExt _redisExt;
public TokenTranslateController(IConfigurationRoot config)//, IConfigurationRoot config) { _config = config; IDatabase redisDataBase = RedisClientSingleton.GetInstance(_config).GetDatabase("Redis_Default"); } public string Post(string value) { redisDataBase.StringSet("TestMvcRedis", value); }
④运行value = TestMvcRedisValue 后得到
随手写的,写得比较糙。