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 这和一般意义上的分布式缓存非常类似, ...
随机推荐
- 一篇文章图文并茂地带你轻松学会 HTML5 storage
html5 storage api localStorage 和 sessionStorage 是 html5 新增的用来存储数据的对象,他们让我们可以以键值对的形式存储信息. 为什么要有 stora ...
- Leetcode(5)-最长回文子串(包含动态规划以及Manacher算法)
给定一个字符串 s,找到 s 中最长的回文子串.你可以假设 s 的最大长度为1000. 示例 1: 输入: "babad" 输出: "bab" 注意: &quo ...
- 前端使用 js 如何实现大文件上传
前端使用 js 如何实现大文件上传 大文件上传 refs xgqfrms 2012-2020 www.cnblogs.com 发布文章使用:只允许注册用户才可以访问!
- ituring 挂了
ituring 挂了 图灵社区 挂了 运行时错误 "/"应用程序中的服务器错误. 运行时错误 说明: 服务器上出现应用程序错误.此应用程序的当前自定义错误设置禁止远程查看应用程序错 ...
- LeetCode 高效刷题路径
LeetCode 高效刷题路径 Hot 100 https://leetcode.com/problemset/hot-100/ https://leetcode-cn.com/problemset/ ...
- NAIO & Node.js All In One
NAIO & Node.js All In One Node.js Tutorials https://nodejs.org/en/docs/ https://nodejs.org/en/do ...
- GitHub Actions
GitHub Actions CI/CD & testing https://github.com/features/actions refs xgqfrms 2012-2020 www.cn ...
- asm movbe 指令
movbe MOVBE 目标操作数,源操作数 复制源操作数的数据,交换字节后,移动数据 假如: movbe eax,(float)1000.0 eax == 0x00007A44 movbe eax, ...
- vue2.0用法以及环境配置
一.配置环境搭建 1.安装node.js (可以去官网看) 2.安装git (推荐看廖雪峰文章,点击查看) 3.安装vue: cmd:npm install vue //最新稳定版本 npm inst ...
- NGK治理机制研究
治理机制是区块链项目的重要设计.随着项目的运行,生态中的参与者需要根据实际运行情况对项目进行必要的更新和升级,以使项目持续良性发展.治理机制的作用是使不同参与者最终达成共识.治理机制直接决定这个网络生 ...