Distributed Cache(分散式快取)-SqlServer
分散式快取是由多個應用伺服器共享的快取,通常作為外部服務儲存在單個應用伺服器上,常用的有SqlServer,Redis,NCache。
分散式快取可以提高ASP.NET Core應用程式的效能和可伸縮性,尤其是應用程式由雲服務或伺服器場託管時。
分散式快取的特點:
- 跨多個伺服器請求,保證一致性。
- 應用程式的伺服器重啟或部署時,快取資料不丟失。
- 不使用本地快取(如果是多個應用伺服器會出現不一致及資料丟失的風險)
Sql Server Distrubuted Cahce configure and application
1、Nuget下載安裝包
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
如果看到如下提示,證明快取表建立成功:
快取表結構:
3、在請求管道中新增DistributedCache(Note:這裡建議ConnectionString,SchemaName,TableName最好寫在配置檔案裡,在本章最後簡單介紹下如果在NetCore console 裡配置使用appsettings.json)
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; }
4、通過建構函式依賴注入IDistributedCache
private readonly IDistributedCache _cacheService; public SqlServerService(IDistributedCache cacheService) { this._cacheService = cacheService; }
最簡單的方式是直接使用IDistributedCache Extension方法,提供了String型別的cache value還是比較常用的。
以下是簡單封裝實現,根據需求更改即可。
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
2、新增appsettings.json檔案,修改property->copy always
"SqlServerDistributedCache": { "ConnectionString": "", "SchemaName": "", "TableName": "" }
3、構建Configuration物件並新增到請求管道
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。
&n