Net Core 缓存系列:
1、NetCore IMemoryCache 内存缓存
2、Distributed Cache(分布式缓存)-SqlServer
3、Distributed Cache(分布式缓存)-Redis
欢迎交流学习!!! GitHub源码
分布式缓存是由多个应用服务器共享的缓存,通常作为外部服务存储在单个应用服务器上,常用的有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; }
View Code
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。