ASP.Net Core 提供了多种类型的缓存,除了内存缓存
和响应缓存
之外,还提供了对 分布式缓存
的支持。在之前的一篇文章中,我讨论了 ASP.Net Core 的内存缓存。在本文中,我们将讨论如何在 ASP.Net Core 中使用分布式缓存,本篇就拿 Redis 和 SQL Server 作为演示。
什么是分布式缓存
分布式缓存
可用于提高应用程序的性能和可伸缩性,通常 分布式缓存
被多个应用服务器共享,在分布式缓存中,缓存的数据不会落在某些个别的web服务器内存中,这些缓存数据采用集中化存储,这样多个应用服务器都可以直接使用,这样做的好处在于,如果任何一个服务器宕机或者停止响应,其他的服务器仍然能够检索缓存的数据。分布式缓存的另一个优点是,缓存的数据在服务器重启后仍然存在,当你的应用集群扩展时,并不会对缓存服务器造成任何影响。
要想在 ASP.NET Core 中使用分布式缓存,需要用到 IDistributedCache 接口,在下一节中,我们将会一起讨论 IDistributedCache 和 IMemoryCache 接口的区别。
IDistributedCache 接口
在.Net Core 中用于分布式缓存的 IDistributedCache
接口要比 单机版的 IMemoryCache
接口更复杂,先来看一下 IMemoryCache 接口定义。
public interface IMemoryCache : IDisposable
{bool TryGetValue(object key, out object value);ICacheEntry CreateEntry(object key);void Remove(object key);
}
IDistributedCache 接口是为 web farm
场景设计的, 它包含了一组同步和异步方法,可用于对缓存的 Add,Remove,Retrieve 操作,下面是 IDistributedCache 接口的定义。
public interface IDistributedCache
{byte[] Get(string key);Task<byte[]> GetAsync(string key);void Set(string key, byte[] value, DistributedCacheEntryOptions options);Task SetAsync(string key, byte[] value, DistributedCacheEntryOptions options);void Refresh(string key);Task RefreshAsync(string key);void Remove(string key);Task RemoveAsync(string key);
}
有一点值得注意,上面的 Set 方法的 value 仅支持 byte[],有点坑哈,当然你要塞入 string 的话, 不用担心,ASP.NET Core 也提供了扩展方法对其进行支持.
如何使用 Redis 作为缓存介质
可以通过 Nuget 来安装如下扩展包,代码如下:
Install-Package Microsoft.Extensions.Caching.Redis
为了能够把 Redis 作为应用底层缓存,需要使用 AddDistributedRedisCache()
扩展方法,下面的代码展示了如何去配置:
public void ConfigureServices(IServiceCollection services)
{services.AddMvc();services.AddDistributedRedisCache(option =>{option.Configuration ="localhost";option.InstanceName ="IDG";});
}
如何注入到 Controller
下面的代码清单展示了如何将 IDistributedCache 注入到 Controller 中并实现从 Redis 中进行插入和读取。
public class DefaultController : Controller
{private readonly IDistributedCache _distributedCache;public HomeController(IDistributedCache distributedCache){_distributedCache = distributedCache;}[HttpGet]public async Task<string> Get(){var cacheKey ="IDG";var data = _distributedCache.GetString(cacheKey);if (!string.IsNullOrEmpty(data)){return data; //returned from Cache}else{string str ="Hello World";_distributedCache.SetString(cacheKey, str);return str;}}
}
如何使用 SqlServer 作为缓存介质
要想将 SqlServer 作为底层的缓存介质,需要通过 Nuget 安装如下包:
Install-Package Microsoft.Extensions.Caching.SqlServer
Install-Package Microsoft.Extensions.Caching.SqlConfig.Tools
如何在 Startup.ConfigureServices()
中做如下配置。
public void ConfigureServices(IServiceCollection services){services.AddControllersWithViews();services.AddDistributedSqlServerCache(x =>{x.ConnectionString = Configuration["ConnectionStrings:Default"];x.SchemaName = "dbo";x.TableName = "IDGCache";});}
接下来通过如下命令在 SqlServer 中生成 Table
来存放缓存数据,代码如下:
dotnet sql-cache create <connection string> <schema> <table>
ASP.Net Core 提供了分布式缓存的高层抽象。因此,无论底层缓存介质是 Redis 还是 SQL Server, IDistributedCache接口都提供了统一并且便捷的操控Cache的API,而且 IDistributedCache 注入到 Controller 中也是非常方便的。
译文链接:https://www.infoworld.com/article/3262990/web-development/how-to-implement-a-distributed-cache-in-aspnet-core.html