.net core使用redis基于StackExchange.Redis教程,具体如下
一.添加引用包
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类
代码如下 | 复制代码 |
publicclassRedisClient : IDisposable { privateIConfigurationRoot _config; privateConcurrentDictionary publicRedisClient(IConfigurationRoot config) { _config = config; _connections =newConcurrentDictionary } /// /// 获取ConnectionMultiplexer /// ///RedisConfig配置文件 /// privateConnectionMultiplexer GetConnect(IConfigurationSection redisConfig) { var redisInstanceName = redisConfig["InstanceName"]; var connStr = redisConfig["Connection"]; return_connections.GetOrAdd(redisInstanceName, p => ConnectionMultiplexer.Connect(connStr)); } /// /// 检查入参数 /// ///RedisConfig配置文件中的 Redis_Default/Redis_6 名称 /// privateIConfigurationSection CheckeConfig(stringconfigName) { IConfigurationSection redisConfig = _config.GetSection("RedisConfig").GetSection(configName); if(redisConfig ==null) { thrownewArgumentNullException($"{configName}找不到对应的RedisConfig配置!"); } var redisInstanceName = redisConfig["InstanceName"]; var connStr = redisConfig["Connection"]; if(string.IsNullOrEmpty(redisInstanceName)) { thrownewArgumentNullException($"{configName}找不到对应的InstanceName"); } if(string.IsNullOrEmpty(connStr)) { thrownewArgumentNullException($"{configName}找不到对应的Connection"); } returnredisConfig; } /// /// 获取数据库 /// /// ///默认为0:优先代码的db配置,其次config中的配置 /// publicIDatabase GetDatabase(stringconfigName =null,int? db =null) { intdefaultDb = 0; IConfigurationSection redisConfig = CheckeConfig(configName); if(db.HasValue) { defaultDb = db.Value; } else { var strDefalutDatabase = redisConfig["DefaultDatabase"]; if(!string.IsNullOrEmpty(strDefalutDatabase) && Int32.TryParse(strDefalutDatabase,outvar intDefaultDatabase)) { defaultDb = intDefaultDatabase; } } returnGetConnect(redisConfig).GetDatabase(defaultDb); }
publicIServer GetServer(stringconfigName =null,intendPointsIndex = 0) { IConfigurationSection redisConfig = CheckeConfig(configName); var connStr = redisConfig["Connection"];
var confOption = ConfigurationOptions.Parse((string)connStr); returnGetConnect(redisConfig).GetServer(confOption.EndPoints[endPointsIndex]); }
publicISubscriber GetSubscriber(stringconfigName =null) { IConfigurationSection redisConfig = CheckeConfig(configName); returnGetConnect(redisConfig).GetSubscriber(); }
publicvoidDispose() { if(_connections !=null&& _connections.Count > 0) { foreach(var itemin_connections.Values) { item.Close(); } } } } |
因为RedisClient 中使用了ConcurrentDictionary
所以,有了RedisClientSingleton.cs类
代码如下 | 复制代码 |
publicclassRedisClientSingleton { privatestaticRedisClient _redisClinet; privateRedisClientSingleton() { }
privatestaticobject_lockObj =newobject(); publicstaticRedisClient GetInstance(IConfigurationRoot config) { if(_redisClinet ==null) { lock(_lockObj) { if(_redisClinet ==null) { _redisClinet =newRedisClient(config); } } } return_redisClinet; } } |
四.测试
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
代码如下 | 复制代码 |
staticvoidMain(string[] args) { var builder =newConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json"); IConfigurationRoot configuration = builder.Build();
var redisClient = RedisClientSingleton.GetInstance(configuration);
var redisDatabase = redisClient.GetDatabase("Redis_Default");
redisDatabase.StringSet("TestStrKey","TestStrValue"); } |
③运行后可以看到
2、web程序
①创建一个core的mvc项目
②修改Startup.cs文件
修改ConfigureServices函数
代码如下 | 复制代码 |
publicvoidConfigureServices(IServiceCollection services) { ... services.AddSingleton(Configuration); ... } |
其中的Configuration是 public IConfigurationRoot Configuration { get; }
③创建一个TestController
在修改构造函数
SimpleRedisExt _redisExt;
代码如下 | 复制代码 |
publicTokenTranslateController(IConfigurationRoot config)//, IConfigurationRoot config) { _config = config; IDatabase redisDataBase = RedisClientSingleton.GetInstance(_config).GetDatabase("Redis_Default"); }
publicstringPost(stringvalue) { redisDataBase.StringSet("TestMvcRedis", value); } |
④运行value = TestMvcRedisValue 后得到
随手写的,写得比较糙。
以上就是本文的全部内容,希望对大家的学习有所帮助