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;
}
}
这里主要说下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();
}
这里是根据环境变量“ASPNETCORE_ENVIRONMENT”读取不同的appsettings文件,比如Development,Staging,Product
4、通过构造函数注入使用IConfiguration对象即可。
完整代码地址: Github。
Distributed Cache(分布式缓存)-SqlServer的更多相关文章
- 第十二节:Asp.Net Core 之分布式缓存(SQLServer和Redis)
一. 整体说明 1. 说明 分布式缓存通常是指在多个应用程序服务器的架构下,作为他们共享的外部服务共享缓存,常用的有SQLServer.Redis.NCache. 特别说明一下:这里的分布式是 ...
- 一个技术汪的开源梦 —— 公共组件缓存之分布式缓存 Redis 实现篇
Redis 安装 & 配置 本测试环境将在 CentOS 7 x64 上安装最新版本的 Redis. 1. 运行以下命令安装 Redis $ wget http://download.redi ...
- Flink分布式缓存Distributed Cache
1 分布式缓存 Flink提供了一个分布式缓存,类似于hadoop,可以使用户在并行函数中很方便的读取本地文件,并把它放在taskmanager节点中,防止task重复拉取. 此缓存的工作机制如下:程 ...
- 分布式缓存HttpRuntime.cache应用到单点登陆中_优化登陆
以前的设计方案,是我们在数据库中放一个表,用作存储验证登陆成功的用户,并且生成用户TOKEN(令牌) 分布式缓存+集群的解决方案图: 相应的代码: DE层中配置文件: receiveTimeout=& ...
- 【开源项目系列】如何基于 Spring Cache 实现多级缓存(同时整合本地缓存 Ehcache 和分布式缓存 Redis)
一.缓存 当系统的并发量上来了,如果我们频繁地去访问数据库,那么会使数据库的压力不断增大,在高峰时甚至可以出现数据库崩溃的现象.所以一般我们会使用缓存来解决这个数据库并发访问问题,用户访问进来,会先从 ...
- 分布式缓存NCache使用
NCache作为缓存优点币Redis有优势,但是收费的所以选用的不多吧.下面简单实操一下: 首先官网下载组件NCache Download Center (alachisoft.com),这里选择企业 ...
- ASP.NET Core 6框架揭秘实例演示[16]:内存缓存与分布式缓存的使用
.NET提供了两个独立的缓存框架,一个是针对本地内存的缓存,另一个是针对分布式存储的缓存.前者可以在不经过序列化的情况下直接将对象存储在应用程序进程的内存中,后者则需要将对象序列化成字节数组并存储到一 ...
- 干掉RedisHelper,请这样用分布式缓存
前言 我们在项目中使用Redis时通常是写一个单例模式的RedisHelper静态类,暴露一些常用的Get.Set等操作,在需要使用地方直接RedisHelper.StringGet(xx,xx)就可 ...
- (转)Ehcache作为分布式缓存的研究
ehcache支持两种拓扑结构,一种是Distributed Caching,另一种是Replicated Caching Distributed Caching 这和一般意义上的分布式缓存非常类似, ...
随机推荐
- Linux内核4.19.1编译
linux内核编译 1.1 大致步骤 下载linux内核4.19.1 官网链接: https://www.kernel.org/ 官网下载经常速度太慢,无法下载,提供另一个链接: http://ftp ...
- Hacker101 CTF-Micro-CMS v2
一.打开网站是这个样子 找到一个登录框,存在注入漏洞 3.我们可以这样更改用户名中的输入: admin' or 1=1 -- 4.错误消息显示Invalid Password,因此我们也应该尝试构造一 ...
- DOM型XSS
打开漏洞页面,随便输入点东西,发现没有啥东西. 但是我们发现我们输入的11,在面的herf 中 看到这儿就很简单了,我们只需要闭合一下,就可以构造出我们的payload了. '><img ...
- 记一次小米手机安装Google Play(其他手机类似)
记一次小米手机安装Google Play(其他手机类似) 最近换了一款小米10青春版,性价比很高,对于开发者而言,手机自带商店的软件内容往往不能满足需求,而需要单独定制习惯性的APP,博主通过最近的尝 ...
- TypeScript Interface vs Types All In One
TypeScript Interface vs Types All In One TypeScript https://www.typescriptlang.org/docs/handbook/adv ...
- Make one your own Online Video Recorder by using WebRTC & vanilla javascript
Make one your own Online Video Recorder by using WebRTC & vanilla javascript Online Video Record ...
- HTTPS clone !== SSH clone
HTTPS clone !== SSH clone https clone bug SSH clone OK testing SSH key https://www.cnblogs.com/xgqfr ...
- CSS Dark Mode
CSS Dark Mode https://kevq.uk/automatic-dark-mode/ https://kevq.uk/how-to-add-css-dark-mode-to-a-web ...
- Python算法_爬楼梯(08)
假设你正在爬楼梯.需要 n 阶你才能到达楼顶. 每次你可以爬 1 或 2 个台阶.你有多少种不同的方法可以爬到楼顶呢? 注意:给定 n 是一个正整数. 示例 1: 输入: 2输出: 2解释: 有两种方 ...
- 生成类库项目时同时生成的pdb文件是什么东东?
英文全称:Program Database File Debug里的PDB是full,保存着调试和项目状态信息.有断言.堆栈检查等代码.可以对程序的调试配置进行增量链接.Release 里的PDB是p ...