分布式缓存的优点:
1.所有web服务器上的缓存数据都是相同的
2.缓存数据在web服务器重启后和部署后仍然存在
3.对数据库的请求变少
缓存主要是针对不经常发生改变并且访问量很大的数据,当数据量很大时,可转移数据库的压力到缓存中。
IDistributedCache接口包含同步和异步方法。 接口允许在分布式缓存实现中添加、检索和删除项。 IDistributedCache接口包含以下方法:
public interface IDistributedCache
{
byte[] Get(string key);
Task<byte[]> GetAsync(string key, CancellationToken token = default(CancellationToken));
void Refresh(string key);
Task RefreshAsync(string key, CancellationToken token = default(CancellationToken));
void Remove(string key);
Task RemoveAsync(string key, CancellationToken token = default(CancellationToken));
void Set(string key, byte[] value, DistributedCacheEntryOptions options);
Task SetAsync(string key, byte[] value, DistributedCacheEntryOptions options, CancellationToken token = default(CancellationToken));
}
Get、 GetAsync
采用字符串键并以byte[]形式检索缓存项(如果在缓存中找到)。
Set、SetAsync
使用字符串键向缓存添加项byte[]形式)。
Refresh、RefreshAsync
根据键刷新缓存中的项,并重置其可调过期超时值(如果有)。
Remove、RemoveAsync
根据键删除缓存项。
项目调用:
1.windows下下载安装redis https://github.com/MSOpenTech/redis/releases

2.下载后解压

3.打开cmd进入到Redis目录

4.执行命令redis-server.exe redis.windows.conf

出现下图显示表示启动成功了

将Redis安装成服务
新打开cmd进入Redis目录执行命令:redis-server.exe --service-install redis.windows.conf,


开始菜单中执行 services.msc 打开服务,启动Redis服务

5.项目中添加Nuget包,搜索Microsoft.Extensions.Caching.Redis

由于项目AspNetCore安装的是2.11版本,Redis安装2.2.0导致报错

6.Redis选择2.11版本安装

安装完成

在Startup.cs中ConfigureServices方法里添加服务:
public void ConfigureServices(IServiceCollection services)
{
//将Redis分布式缓存服务添加到服务中
services.AddDistributedRedisCache(options =>
{
//用于连接Redis的配置
options.Configuration = "localhost";// Configuration.GetConnectionString("RedisConnectionString");
//Redis实例名RedisDistributedCache
options.InstanceName = "RedisDistributedCache";
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
Demo:
private IDistributedCache _Cache;
/// <summary>
/// 构造注入
/// </summary>
/// <param name="Cache"></param>
public ValuesController(IDistributedCache Cache)
{
_Cache = Cache;
}
// Index api/values
[HttpGet]
public ActionResult<IEnumerable<string>> Index()
{
//获取缓存
var key = Encoding.UTF8.GetString(_Cache.Get("ImagePropertyKey"));
if (string.IsNullOrEmpty(key))
{
byte[] val = null;
val = Encoding.UTF8.GetBytes("ImageProertyValue");
DistributedCacheEntryOptions options = new DistributedCacheEntryOptions();
//设置绝对过期时间 两种写法
options.AbsoluteExpiration = DateTime.Now.AddMinutes(30);
// options.SetAbsoluteExpiration(DateTime.Now.AddMinutes(30));
//设置滑动过期时间 两种写法
options.SlidingExpiration = TimeSpan.FromSeconds(30);
//options.SetSlidingExpiration(TimeSpan.FromSeconds(30));
//添加缓存
_Cache.Set(key, val, options);
//刷新缓存
_Cache.Refresh(key);
}
else {
//移除缓存
_Cache.Remove("ImagePropertyKey");
}
return new string[] { "value1", "value2" };
}
网友评论