.net core使用redis基于StackExchange.Redis

四个拥有:无论你有多弱或多强,一定要拥有真正爱你的人,拥有知心的朋友,拥有向上的事业,拥有温暖的住所。

.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类

public class RedisClient : IDisposable
{
 private IConfigurationRoot _config;
 private ConcurrentDictionary<string, ConnectionMultiplexer> _connections;
 public RedisClient(IConfigurationRoot config)
 {
  _config = config;
  _connections = new ConcurrentDictionary<string, ConnectionMultiplexer>();
 }
 /// <summary>
 /// 获取ConnectionMultiplexer
 /// </summary>
 /// <param name="redisConfig">RedisConfig配置文件</param>
 /// <returns></returns>
 private ConnectionMultiplexer GetConnect(IConfigurationSection redisConfig)
 {
  var redisInstanceName = redisConfig["InstanceName"];
  var connStr = redisConfig["Connection"];
  return _connections.GetOrAdd(redisInstanceName, p => ConnectionMultiplexer.Connect(connStr));
 }
 /// <summary>
 /// 检查入参数
 /// </summary>
 /// <param name="configName">RedisConfig配置文件中的 Redis_Default/Redis_6 名称</param>
 /// <returns></returns>
 private IConfigurationSection CheckeConfig(string configName)
 {
  IConfigurationSection redisConfig = _config.GetSection("RedisConfig").GetSection(configName);
  if (redisConfig == null)
  {
   throw new ArgumentNullException($"{configName}找不到对应的RedisConfig配置!");
  }
  var redisInstanceName = redisConfig["InstanceName"];
  var connStr = redisConfig["Connection"];
  if (string.IsNullOrEmpty(redisInstanceName))
  {
   throw new ArgumentNullException($"{configName}找不到对应的InstanceName");
  }
  if (string.IsNullOrEmpty(connStr))
  {
   throw new ArgumentNullException($"{configName}找不到对应的Connection");
  }
  return redisConfig;
 }
 /// <summary>
 /// 获取数据库
 /// </summary>
 /// <param name="configName"></param>
 /// <param name="db">默认为0:优先代码的db配置,其次config中的配置</param>
 /// <returns></returns>
 public IDatabase GetDatabase(string configName = null, int? db = null)
 {
  int defaultDb = 0;
  IConfigurationSection redisConfig = CheckeConfig(configName);
  if (db.HasValue)
  {
   defaultDb = db.Value;
  }
  else
  {
   var strDefalutDatabase = redisConfig["DefaultDatabase"];
   if (!string.IsNullOrEmpty(strDefalutDatabase) && Int32.TryParse(strDefalutDatabase, out var intDefaultDatabase))
   {
    defaultDb = intDefaultDatabase;
   }
  }
  return GetConnect(redisConfig).GetDatabase(defaultDb);
 }

 public IServer GetServer(string configName = null, int endPointsIndex = 0)
 {
  IConfigurationSection redisConfig = CheckeConfig(configName);
  var connStr = redisConfig["Connection"];

  var confOption = ConfigurationOptions.Parse((string)connStr);
  return GetConnect(redisConfig).GetServer(confOption.EndPoints[endPointsIndex]);
 }

 public ISubscriber GetSubscriber(string configName = null)
 {
  IConfigurationSection redisConfig = CheckeConfig(configName);
  return GetConnect(redisConfig).GetSubscriber();
 }

 public void Dispose()
 {
  if (_connections != null && _connections.Count > 0)
  {
   foreach (var item in _connections.Values)
   {
    item.Close();
   }
  }
 }
}

因为RedisClient 中使用了ConcurrentDictionary
所以,有了RedisClientSingleton.cs类

public class RedisClientSingleton
{
 private static RedisClient _redisClinet;
 private RedisClientSingleton() { }

 private static object _lockObj = new object();
 public static RedisClient GetInstance(IConfigurationRoot config)
 {
  if (_redisClinet == null)
  {
   lock (_lockObj)
   {
    if (_redisClinet == null)
    {
     _redisClinet = new RedisClient(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

static void Main(string[] args)
 {
   var builder = new ConfigurationBuilder()
    .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函数

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 后得到

随手写的,写得比较糙。

本文.net core使用redis基于StackExchange.Redis到此结束。用我们的奋斗和梦想扬起青春的船帆,当我们努力拼搏地摇浆时,成功的闸门也会慢慢地再为我们打开,我们将享受一份青春的美好,收获一份成功的喜悦。小编再次感谢大家对我们的支持!

标签: core net