天天看點

Distributed Cache(分布式緩存)-SqlServer

Distributed Cache(分布式緩存)-SqlServer

分布式緩存是由多個應用伺服器共享的緩存,通常作為外部服務存儲在單個應用伺服器上,常用的有SqlServer,Redis,NCache。

分布式緩存可以提高ASP.NET Core應用程式的性能和可伸縮性,尤其是應用程式由雲服務或伺服器場托管時。

分布式緩存的特點:

  • 跨多個伺服器請求,保證一緻性。
  • 應用程式的伺服器重新開機或部署時,緩存資料不丢失。
  • 不使用本地緩存(如果是多個應用伺服器會出現不一緻及資料丢失的風險)

Sql Server Distrubuted Cahce configure and application

1、Nuget下載下傳安裝包

Distributed Cache(分布式緩存)-SqlServer

 2、使用sql-cache 工具建立緩存清單

     Win+r 打開cmd指令,輸入如下指令,建立緩存表,

dotnet sql-cache create "Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=DistCache;Integrated Security=True;" dbo TestCache      

如遇到以下error,需要安裝dotnet-sql-cache,指令如下。(Note: NetCore 3.1 對應的dotnet-sql-chche version 3.1.13)

dotnet tool install --global dotnet-sql-cache
      
Distributed Cache(分布式緩存)-SqlServer

如果看到如下提示,證明緩存表建立成功:

Distributed Cache(分布式緩存)-SqlServer

緩存表結構:

Distributed Cache(分布式緩存)-SqlServer

3、在請求管道中添加DistributedCache(Note:這裡建議ConnectionString,SchemaName,TableName最好寫在配置檔案裡,在本章最後簡單介紹下如果在NetCore console 裡配置使用appsettings.json)

Distributed Cache(分布式緩存)-SqlServer
Distributed Cache(分布式緩存)-SqlServer
public static IServiceCollection ConfigureServices(this IServiceCollection services)
{
            var configuration = BuildConfiguration();
            services.AddSingleton<IConfiguration>(configuration);
            services.AddDistributedSqlServerCache(options=> 
            {
                options.ConnectionString = configuration["SqlServerDistributedCache:ConnectionString"];
                options.SchemaName =configuration["SqlServerDistributedCache:SchemaName"];
                options.TableName = configuration["SqlServerDistributedCache:TableName"];
            });
            services.AddTransient<ISqlServerService, SqlServerService>();
            return services;
}      

View Code

4、通過構造函數依賴注入IDistributedCache

private readonly IDistributedCache _cacheService;

public SqlServerService(IDistributedCache cacheService)
{
      this._cacheService = cacheService;
}      

最簡單的方式是直接使用IDistributedCache Extension方法,提供了String類型的cache value還是比較常用的。

Distributed Cache(分布式緩存)-SqlServer

以下是簡單封裝實作,根據需求更改即可。

Distributed Cache(分布式緩存)-SqlServer
Distributed Cache(分布式緩存)-SqlServer
public class SqlServerService: ISqlServerService
    {
        private readonly IDistributedCache _cacheService;

        public SqlServerService(IDistributedCache cacheService)
        {
            this._cacheService = cacheService;
        }

        public async Task SetAsync(string key, byte[] value, object expiration = null, bool isAbsoluteExpiration = false)
        {
            var options = this.BuildDistributedCacheEntryOptions(expiration, isAbsoluteExpiration);
            await _cacheService.SetAsync(key, value, options);
        }

        public async Task SetAsync(string key, string value, object expiration = null, bool isAbsoluteExpiration = false)
        {
            var options = this.BuildDistributedCacheEntryOptions(expiration, isAbsoluteExpiration);
            await _cacheService.SetStringAsync(key, value, options);
        }

        public async Task<byte[]> GetAsync(string key)
        {
            return await _cacheService.GetAsync(key);
        }

        public async Task<string> GetStringAsync(string key)
        {
            return await _cacheService.GetStringAsync(key);
        }

        public async Task RemoveAsync(string key)
        {
            await _cacheService.RemoveAsync(key);
        }

        public async Task RefreshAsync(string key)
        {
            await _cacheService.RefreshAsync(key);
        }

        private DistributedCacheEntryOptions BuildDistributedCacheEntryOptions(object expiration = null, bool isAbsoluteExpiration = false)
        {
            var options = new DistributedCacheEntryOptions();
            if (expiration != null)
            {
                if (expiration is TimeSpan)
                {
                    if (isAbsoluteExpiration)
                        options.SetAbsoluteExpiration((TimeSpan)expiration);
                    else
                        options.SetSlidingExpiration((TimeSpan)expiration);
                }
                else if (expiration is DateTimeOffset)
                {
                    options.SetAbsoluteExpiration((DateTimeOffset)expiration);
                }
                else
                {
                    throw new NotSupportedException("Not support current expiration object settings.");
                }
            }
            return options;
        }
    }      

View Code

這裡主要說下DistributedCacheEntryOptions這個類,作用是設定緩存項的過期時間

public class DistributedCacheEntryOptions
{
    public DistributedCacheEntryOptions()
    public DateTimeOffset? AbsoluteExpiration { get; set; }//絕對過期時間
    public TimeSpan? AbsoluteExpirationRelativeToNow { get; set; }//絕對過期時間
    public TimeSpan? SlidingExpiration { get; set; } //滑動過期時間(如果在滑動過期時間内重新整理,将重新設定滑動過去時間,對應IDistributedCache中的Refresh方法)
}      

OK,Sql Server IDistributeCache 就介紹到這裡。

附加:NetCore Console 中使用appsettings.json檔案

1、Nuget下載下傳安裝packages

Distributed Cache(分布式緩存)-SqlServer

 2、添加appsettings.json檔案,修改property->copy always

"SqlServerDistributedCache": {
    "ConnectionString": "",
    "SchemaName": "",
    "TableName": ""
  }      

3、建構Configuration對象并添加到請求管道

Distributed Cache(分布式緩存)-SqlServer
Distributed Cache(分布式緩存)-SqlServer
public static IServiceCollection ConfigureServices(this IServiceCollection services)
{
            var configuration = BuildConfiguration();
            services.AddSingleton<IConfiguration>(configuration);
            services.AddDistributedSqlServerCache(options=> 
            {
                options.ConnectionString = configuration["SqlServerDistributedCache:ConnectionString"];
                options.SchemaName = configuration["SqlServerDistributedCache:SchemaName"];
                options.TableName = configuration["SqlServerDistributedCache:TableName"];
            });
            services.AddTransient<ISqlServerService, SqlServerService>();
            return services;
}

        private static IConfigurationRoot BuildConfiguration()
        {
            var env = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");

            var builder = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile($"appsettings.json", true, true)
                .AddJsonFile($"appsettings.{env}.json", true, true)
                .AddEnvironmentVariables();
            return builder.Build();
        }      

View Code

這裡是根據環境變量“ASPNETCORE_ENVIRONMENT”讀取不同的appsettings檔案,比如Development,Staging,Product

4、通過構造函數注入使用IConfiguration對象即可。

完整代碼位址: Github。

c#