. Net core uses redis Based on StackExchange. Redis, stackexchange. redis

Source: Internet
Author: User
Tags redis tutorial

. Net core uses redis Based on StackExchange. Redis, stackexchange. redis

. Net core using redis Based on StackExchange. Redis tutorial, details are as follows

1. Add a 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 Encapsulation
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> /// obtain 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 the input parameters /// </summary> /// <param name = "configName"> RedisConfig configuration file Redis_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} cannot find the corresponding RedisConfig configuration! ");} Var redisInstanceName = redisConfig [" InstanceName "]; var connStr = redisConfig [" Connection "]; if (string. isNullOrEmpty (redisInstanceName) {throw new ArgumentNullException ($ "{configName} cannot find the corresponding InstanceName");} if (string. isNullOrEmpty (connStr) {throw new ArgumentNullException ($ "{configName} cannot find the corresponding Connection");} return redisConfig ;} /// <summary> /// obtain the database /// </summary> /// <param name = "c OnfigName "> </param> // <param name =" db "> default value: 0: db configuration with priority code, in config, configure </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 = intdefadatabase database;} return GetConnect (redisConfig ). getDatabase (defaultDb);} public IServer GetServer (string configName = null, int endPointsIndex = 0) {IConfigurationSection redisConfig = CheckeConfig (configName); var connStr = redisConfig ["Connection"]; var confOption = C OnfigurationOptions. 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 the RedisClient uses ConcurrentDictionary
Therefore, with the 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; }}

Iv. Test

1. Console Program

1) create a Controller Program
2) Add a reference package
Microsoft. Extensions. Configuration
Microsoft. Extensions. Configuration. Json
3) add etettings. 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 the Program class

① Add and 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 programs

① Create a core mvc Project
② Modify the Startup. cs File
Modify ConfigureServices Functions

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

The Configuration here is public IConfigurationRoot Configuration {get ;}

③ Create a TestController
Modify the 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);}

④ Run value = tew.vcredisvalue and get

As you write, it is rough.

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.