分布式缓存是由多个应用服务器共享的缓存,通常作为外部服务存储在单个应用服务器上,常用的有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的更多相关文章

  1. 第十二节:Asp.Net Core 之分布式缓存(SQLServer和Redis)

    一. 整体说明 1. 说明 分布式缓存通常是指在多个应用程序服务器的架构下,作为他们共享的外部服务共享缓存,常用的有SQLServer.Redis.NCache.     特别说明一下:这里的分布式是 ...

  2. 一个技术汪的开源梦 —— 公共组件缓存之分布式缓存 Redis 实现篇

    Redis 安装 & 配置 本测试环境将在 CentOS 7 x64 上安装最新版本的 Redis. 1. 运行以下命令安装 Redis $ wget http://download.redi ...

  3. Flink分布式缓存Distributed Cache

    1 分布式缓存 Flink提供了一个分布式缓存,类似于hadoop,可以使用户在并行函数中很方便的读取本地文件,并把它放在taskmanager节点中,防止task重复拉取. 此缓存的工作机制如下:程 ...

  4. 分布式缓存HttpRuntime.cache应用到单点登陆中_优化登陆

    以前的设计方案,是我们在数据库中放一个表,用作存储验证登陆成功的用户,并且生成用户TOKEN(令牌) 分布式缓存+集群的解决方案图: 相应的代码: DE层中配置文件: receiveTimeout=& ...

  5. 【开源项目系列】如何基于 Spring Cache 实现多级缓存(同时整合本地缓存 Ehcache 和分布式缓存 Redis)

    一.缓存 当系统的并发量上来了,如果我们频繁地去访问数据库,那么会使数据库的压力不断增大,在高峰时甚至可以出现数据库崩溃的现象.所以一般我们会使用缓存来解决这个数据库并发访问问题,用户访问进来,会先从 ...

  6. 分布式缓存NCache使用

    NCache作为缓存优点币Redis有优势,但是收费的所以选用的不多吧.下面简单实操一下: 首先官网下载组件NCache Download Center (alachisoft.com),这里选择企业 ...

  7. ASP.NET Core 6框架揭秘实例演示[16]:内存缓存与分布式缓存的使用

    .NET提供了两个独立的缓存框架,一个是针对本地内存的缓存,另一个是针对分布式存储的缓存.前者可以在不经过序列化的情况下直接将对象存储在应用程序进程的内存中,后者则需要将对象序列化成字节数组并存储到一 ...

  8. 干掉RedisHelper,请这样用分布式缓存

    前言 我们在项目中使用Redis时通常是写一个单例模式的RedisHelper静态类,暴露一些常用的Get.Set等操作,在需要使用地方直接RedisHelper.StringGet(xx,xx)就可 ...

  9. (转)Ehcache作为分布式缓存的研究

    ehcache支持两种拓扑结构,一种是Distributed Caching,另一种是Replicated Caching Distributed Caching 这和一般意义上的分布式缓存非常类似, ...

随机推荐

  1. Excel导出时设置单元格的格式为文本

    问题: 用excel导出数据时,如何设置单元格格式的数字分类为"文本",默认是"常规"? 比如:导出编码0235A089,在Excel查看默认显示的是没有前面的 ...

  2. Linux 网络协议栈开发基础篇—— 网桥br0

    一.桥接的概念 简单来说,桥接就是把一台机器上的若干个网络接口"连接"起来.其结果是,其中一个网口收到的报文会被复制给其他网口并发送出去.以使得网口之间的报文能够互相转发. 交换机 ...

  3. Apple 产品反人类的设计 All In One

    Apple 产品反人类的设计 All In One 用户体验 shit rank WTF rank iPhone 更换铃声 WTF, 这么简单的一个功能搞得太复杂了 使用要下载 1.6 G的库乐队 A ...

  4. robots.txt

    robots.txt A robots.txt file tells search engine crawlers which pages or files the crawler can or ca ...

  5. Flutter 设置input边框

    example 1 import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp ext ...

  6. 「NGK每日快讯」12.31日NGK第58期官方快讯!

  7. golang官方嵌入文件到可执行程序

    目录 前言 示例程序 嵌入文件直接访问 嵌入文件列表 总结 前言 在go官方出嵌入文件的方法前我在网上找过,并且自己还研究过,虽然没有问题,但是既然官方支持还是用起来吧. 看了下go源码embed/e ...

  8. HGAME apache

    HGAME apache Linux下六十四位可执行文件 IDA找主函数 输入长度为35的字符串,经过一次函数处理,之后if条件函数的返回值为1,就能判定输入就是flag 函数sub_1447的参数 ...

  9. java初学者必看之构造方法详细解读

    java初学者必看之构造方法详细解读 构造方法是专门用来创建对象的方法,当我们通过关键字new来创建对象时,其实就是在调用构造方法. 格式 public 类名称(参数类型 参数名称){ 方法体 } 注 ...

  10. 蓝绿部署、金丝雀发布(灰度发布)、A/B测试

    本文转载自蓝绿部署.金丝雀发布(灰度发布).A/B测试的准确定义 概述 蓝绿部署.A/B测试.金丝雀发布,以及灰度发布.流量切分等,经常被混为一谈,影响沟通效率. 根本原因是这些名词经常出现,人们耳熟 ...