.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擴展,要用新的!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章