.NET使用分布式缓存(SQL Server 示例)Session
文章参考:https://docs.microsoft.com/zh-cn/aspnet/core/performance/caching/distributed?view=aspnetcore-3.1 .NET Core 3.1
比较关键的一点是创建表(注:在使用Session的时候,Session值也会存在缓存当中)
第一步,命令行运行,添加工具:
>dotnet tool install --global dotnet-sql-cache
如果报错,类似下面的,说明是版本没有对上,我之前是3.1.5安装3.1.9出现,按照提示更新一下就好
It was not possible to find any compatible framework version The framework 'Microsoft.NETCore.App', version '3.1.9' was not found.
111
第二步,命令行创建缓存表
dotnet sql-cache create "Data Source=xxx.xxx.xxx.xxx;Initial Catalog=XX;User ID=XX;Password=XXX" dbo 表名
检查一下就完成了。
第三步,代码中的扩展,先NuGet安装 Microsoft.Extensions.Caching.Abstractions、Microsoft.Extensions.Caching.SqlServer
services.AddDistributedSqlServerCache(options => { options.ConnectionString = Configuration["DB:DistCache_ConnectionString"];//数据库链接 options.SchemaName = "dbo"; options.TableName = "CacheTb";//表名 });
测试,先注入:
private IDistributedCache _cache; public TestController(IDistributedCache cache) { _cache = cache; }
action调用与输出:
public IActionResult Info() { _cache.Set("test", Encoding.UTF8.GetBytes("1q1q")); var h=this.Request.Headers; var str = "Info\r\n"; foreach (var s in h) { str += s.Key + ":" + s.Value + "\r\n"; } return Content(str); } public IActionResult Info2() { var h = this.Request.Headers; var str = "Info2\r\n"; foreach (var s in h) { str += s.Key + ":" + s.Value + "\r\n"; } str += "cache:" + Encoding.UTF8.GetString(_cache.Get("test")); return Content(str); }
结果,大功告成:
、
扩展补充:Microsoft.Extensions.Caching.StackExchangeRedis和Microsoft.Extensions.Caching.Redis的区别
从依赖看,Microsoft.Extensions.Caching.StackExchangeRedis比Microsoft.Extensions.Caching.Redis使用的StackExchange高,且Microsoft.Extensions.Caching.Redis的组件已经完成使命不在更新
使用新的.NETCore的Redis扩展,要用新的!
因缘际会的相遇,自当有非同寻常的结局
QQ交流群:110826636