. net core uses redis based on stackexchange.redis

Time:2021-10-20

. net core uses redis based on stackexchange.redis tutorial, as follows

1、 Add reference package

StackExchange.Redis
Microsoft.Extensions.Configuration

2、 Modify the configuration file 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: "
  }
 }
}

3、 Simple packaging
Redisclient.cs class

public class RedisClient : IDisposable
{
 private IConfigurationRoot _config;
 private ConcurrentDictionary<string, ConnectionMultiplexer> _connections;
 public RedisClient(IConfigurationRoot config)
 {
  _config = config;
  _connections = new ConcurrentDictionary<string, ConnectionMultiplexer>();
 }
 /// <summary>
 ///Get connectionmultiplexer
 /// </summary>
 ///< param name = "redisconfig" > redisconfig configuration file < / 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>
 ///Check in parameters
 /// </summary>
 ///< param name = "configname" > redis in redisconfig configuration file_ Default/Redis_ 6 name < / param >
 /// <returns></returns>
 private IConfigurationSection CheckeConfig(string configName)
 {
  IConfigurationSection redisConfig = _config.GetSection("RedisConfig").GetSection(configName);
  if (redisConfig == null)
  {
   Throw new argumentnullexception ($"{configname} can't find the corresponding redisconfig configuration!");
  }
  var redisInstanceName = redisConfig["InstanceName"];
  var connStr = redisConfig["Connection"];
  if (string.IsNullOrEmpty(redisInstanceName))
  {
   Throw new argumentnullexception ($"{configname} can't find the corresponding InstanceName");
  }
  if (string.IsNullOrEmpty(connStr))
  {
   Throw new argumentnullexception ($"{configname} cannot find the corresponding connection");
  }
  return redisConfig;
 }
 /// <summary>
 ///Get database
 /// </summary>
 /// <param name="configName"></param>
 ///< param name = "DB" > the default is 0: DB configuration of priority code, followed by configuration in 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();
   }
  }
 }
}

Because concurrent dictionary is used in redisclient
Therefore, there is redisclientsingleton.cs class


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;
 }
}

4、 Testing

1. Console program

1) Create a controller program
2) Add reference package
Microsoft.Extensions.Configuration
Microsoft.Extensions.Configuration.Json
3) Add appsettings.json

Add the following


"RedisConfig": {
 "Redis_Default": {
  "Connection": "127.0.0.1:6379", 
  "InstanceName": "Redis1:"
 },
 "Redis_6": {
  "Connection": "127.0.0.1:6379",
  "DefaultDatabase": 6,
  "InstanceName": "Redis2:"
 }
 }

4) Modify program class

① Add reference using microsoft.extensions.configuration;
② Modify 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");
} 

③ After running, you can see

2. Web program

① Create a core MVC project
② Modify the startup.cs file
Modifying the configureservices function


public void ConfigureServices(IServiceCollection services)
{
 ...
 services.AddSingleton(Configuration);
 ...
}

Where configuration is public iconfigurationroot configuration {get;}

③ Create a testcontroller
Modifying constructor
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);
}

④ Obtained after running value = testmvcreredisvalue

It’s written casually. It’s rough.

The above is the whole content of this article. I hope it will be helpful to your study, and I hope you can support developpaer.

Recommended Today

Springboot + mybatis + Vue (I), create the project

Springboot + mybatis + Vue (I), create the projectSpringboot + mybatis + Vue (II) to implement the interfaceSpringboot + mybatis + Vue (III). Curd is realized through Axios Intelij create project Do not click mysql, pol There is no dependency on MySQL in XML <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> add as maven project Or restart, […]