CSRedisCore是國內大佬出品的一個Redis-Cli-SDK。
Github地址:https://github.com/2881099/csredis
使用此插件作為分布式緩存也十分簡單。
一、asp.net core 3.0中使用分布式緩存。
注意:IDistributedCache是asp.net core中提供的緩存接口。提供了一些基本的方法。
使用Caching.CSRedis可以方便的實現IDistributedCache接口。
// 通過Caching.CSRedis實現IDistributedCache
services.AddSingleton<IDistributedCache>(new CSRedisCache(new CSRedisClient("127.0.0.1:6379")));
此時就可以在構造函數中注入IDistributedCache接口使用了。
public WeatherForecastController(ILogger<WeatherForecastController> logger, IDistributedCache distributedCache) { _logger = logger; _distributedCache = distributedCache; }
[HttpGet] public IEnumerable<WeatherForecast> GetDistributeCacheData(string key) { var cache = _distributedCache.Get(key); if (cache == null) { // 這里應該上鎖,否則同時會有多個請求,單機測試無所謂。 // 模擬獲取數據 Thread.Sleep(1000); var result = GetDataByDatabase(key); //放到緩存。 _distributedCache.Set(key, JsonSerializer.SerializeToUtf8Bytes(result)); return result; } else { return JsonSerializer.Deserialize<WeatherForecast[]>(cache); } }
使用起來十分簡單。
二、使用Session。
asp.net core 3.0中,使用Session是需要IDistributedCache支持的,即使在單機中使用,也要使用基於內存的分布式緩存。
// 如果不實現IDistributedCache將會異常。
services.AddSession();
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseSession();
}
雖然我在上面注入了IDistributedCache接口的實現,已經可以使用Session了,但是我不能區分數據Redis和SessionRedis容器,Session和其他所有的緩存都將放在一個Redist容器中。
要解決這個問題,則需要注入新的接口。
還是基於CSRedisCore修改。
以下基於Caching.CSRedis的源碼修改。
// 繼承分布式緩存接口。
public interface IDistributedSessionCache : IDistributedCache
使用自定義類繼承默認實現。
/// <summary> /// 自定義RedisSession緩存。 /// </summary> public class DistributedRedisSessionStore : DistributedSessionStore { /// <summary> /// 構造函數。 /// </summary> /// <param name="cache">自定義RedisSession緩存,此處使用繼承默認接口的自定義接口。</param> /// <param name="loggerFactory">日志工廠。</param> public DistributedRedisSessionStore(IDistributedSessionCache cache, ILoggerFactory loggerFactory) : base(cache, loggerFactory) { } }
擴展依賴注入方法
public static IServiceCollection AddRedisSession(this IServiceCollection services) { services.TryAddTransient<ISessionStore, DistributedRedisSessionStore>(); services.AddDataProtection(); return services; }
依賴注入方法
// 連接Redis的容器,此時6380端口。
services.AddSingleton<IDistributedSessionCache>(new CSRedisSessionCache(new CSRedisClient("127.0.0.1:6380"))); services.AddRedisSession();
一個簡單的測試方法
[HttpGet] public IActionResult GetSessionData(string key) { var msg = HttpContext.Connection.LocalPort.ToString(); DateTime dateTime = default; if (HttpContext.Session.TryGetValue(key, out var value)) dateTime = JsonSerializer.Deserialize<DateTime>(value); else { dateTime = DateTime.Now; HttpContext.Session.Set(key, JsonSerializer.SerializeToUtf8Bytes(dateTime)); } _logger.LogInformation($"本次連接端口{msg},通過Session獲得時間值{dateTime}"); return new JsonResult(dateTime); }
此時,我在docker停止了6379(普通數據緩存容器),Session依然沒有問題。
普通數據容器已經掛了
分別啟用端口5002和5003,進行分布式session是否有效。
可以看到是有效的。
區分Session容器和普通數據緩存的代碼。
github: https://github.com/yeqifeng2288/Microsoft.Extensions.Caching.CSRedis.Session