您好,登錄后才能下訂單哦!
這篇文章主要介紹了.net core如何使用redis基于StackExchange.Redis,具有一定借鑒價(jià)值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。
一.添加引用包
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> /// 檢查入?yún)?shù) /// </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}找不到對應(yīng)的RedisConfig配置!"); } var redisInstanceName = redisConfig["InstanceName"]; var connStr = redisConfig["Connection"]; if (string.IsNullOrEmpty(redisInstanceName)) { throw new ArgumentNullException($"{configName}找不到對應(yīng)的InstanceName"); } if (string.IsNullOrEmpty(connStr)) { throw new ArgumentNullException($"{configName}找不到對應(yīng)的Connection"); } return redisConfig; } /// <summary> /// 獲取數(shù)據(jù)庫 /// </summary> /// <param name="configName"></param> /// <param name="db">默認(rèn)為0:優(yōu)先代碼的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(); } } } }
因?yàn)镽edisClient 中使用了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)創(chuàng)建一個(gè)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"); }
③運(yùn)行后可以看到
2、web程序
①創(chuàng)建一個(gè)core的mvc項(xiàng)目
②修改Startup.cs文件
修改ConfigureServices函數(shù)
public void ConfigureServices(IServiceCollection services) { ... services.AddSingleton(Configuration); ... }
其中的Configuration是 public IConfigurationRoot Configuration { get; }
③創(chuàng)建一個(gè)TestController
在修改構(gòu)造函數(shù)
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); }
④運(yùn)行value = TestMvcRedisValue 后得到
隨手寫的,寫得比較糙。
感謝你能夠認(rèn)真閱讀完這篇文章,希望小編分享的“.net core如何使用redis基于StackExchange.Redis”這篇文章對大家有幫助,同時(shí)也希望大家多多支持億速云,關(guān)注億速云行業(yè)資訊頻道,更多相關(guān)知識等著你來學(xué)習(xí)!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。