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 这和一般意义上的分布式缓存非常类似, ...
随机推荐
- Jenkins 安装与部署详细教程
一.概述 Jenkins 的前身是 Hudson 是一个可扩展的持续集成引擎.Jenkins 是一款开源 CI&CD 软件,用于自动化各种任务,包括构建.测试和部署软件.Jenkins 支持各 ...
- Leetcode(870)-优势洗牌
给定两个大小相等的数组 A 和 B,A 相对于 B 的优势可以用满足 A[i] > B[i] 的索引 i 的数目来描述. 返回 A 的任意排列,使其相对于 B 的优势最大化. 示例 1: 输入: ...
- bzoj1013球形空间产生器sphere 高斯消元(有系统差的写法
Description 有一个球形空间产生器能够在n维空间中产生一个坚硬的球体.现在,你被困在了这个n维球体中,你只知道球面上n+1个点的坐标,你需要以最快的速度确定这个n维球体的球心坐标,以便于摧毁 ...
- 快速搞懂.NET 5/.NET Core应用程序的发布部署
.NET Framework时代,.NET 应用程序大多直接部署运行在Windows服务器上,当然也可以通过Mono部署运行在Linux上.无论部署exe,还是IIS站点.或是Windows Serv ...
- Windows 10 自带 free 屏幕截图/录像软件 Game Bar! 不仅仅是game-游戏呦! 高清晰,高保真,perfect!不仅仅是游戏呦!
good news! good news! good news! 重要的事情说三遍! Windows 10 自带 屏幕截图/录像软件 Game Bar! 以后再也不用第三方的 盗版软件了! 对于Wi ...
- Python Web Framework All In One
Python Web Framework All In One Django and Flask are the top Python web frameworks so far. Django ht ...
- input support upload excel only
input support upload excel only demo https://codepen.io/xgqfrms/pen/vYONpLB <!-- <input placeh ...
- NGK的发行量是多少?NGK销毁机制是怎么样的?
代币销毁(Coin Burning),是指将代币从流通中永久性去除.换句话说,被销毁的代币相当于被永久性冻结,再也无法流入市场.那为什么要进行代币销毁呢? 销毁加密货币,可以使剩余加密货币的价值升高, ...
- 27_MySQL数字函数(重点)
/* SALES部门中工龄超过20年的,底薪增加10% SALES部门中工龄不满20年的,底薪增加5% ACCOUNTING部门,底薪增加300元 RESEARCH部门里低于部门平均底薪的,底薪增加2 ...
- [Android搞机]修改build.prop解决类原生无法链接12、13信道wifi问题
最近xda找包刷了个机,发现没法搜到12.13信道.所有未本地化的类原生都有此问题. root后打开/system/build.prop 可以用 在build.prop中加入以下几句,重启即可连接12 ...