• 欢迎访问开心洋葱网站,在线教程,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站,欢迎加入开心洋葱 QQ群
  • 为方便开心洋葱网用户,开心洋葱官网已经开启复制功能!
  • 欢迎访问开心洋葱网站,手机也能访问哦~欢迎加入开心洋葱多维思维学习平台 QQ群
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏开心洋葱吧~~~~~~~~~~~~~!
  • 由于近期流量激增,小站的ECS没能经的起亲们的访问,本站依然没有盈利,如果各位看如果觉着文字不错,还请看官给小站打个赏~~~~~~~~~~~~~!

Distributed Cache(分布式缓存)-SqlServer

Cache 云霄宇霁 1947次浏览 0个评论

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下载安装包

Distributed Cache(分布式缓存)-SqlServer

 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

Distributed Cache(分布式缓存)-SqlServer

如果看到如下提示,证明缓存表创建成功:

Distributed Cache(分布式缓存)-SqlServer

缓存表结构:

Distributed Cache(分布式缓存)-SqlServer

3、在请求管道中添加DistributedCache(Note:这里建议ConnectionString,SchemaName,TableName最好写在配置文件里,在本章最后简单介绍下如果在NetCore console 里配置使用appsettings.json

Distributed Cache(分布式缓存)-SqlServer

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还是比较常用的。

Distributed Cache(分布式缓存)-SqlServer

以下是简单封装实现,根据需求更改即可。

Distributed Cache(分布式缓存)-SqlServer

 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

Distributed Cache(分布式缓存)-SqlServer

 2、添加appsettings.json文件,修改property->copy always

"SqlServerDistributedCache": {
    "ConnectionString": "",
    "SchemaName": "",
    "TableName": ""
  }

3、构建Configuration对象并添加到请求管道

Distributed Cache(分布式缓存)-SqlServer

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。

 


开心洋葱 , 版权所有丨如未注明 , 均为原创丨未经授权请勿修改 , 转载请注明Distributed Cache(分布式缓存)-SqlServer
喜欢 (0)

您必须 登录 才能发表评论!

加载中……