Redis使用
-
-
//分布式缓存
services.AddStackExchangeRedisCache(options =>
{
//获取连接字符串
options.Configuration = Configuration.GetSection("RedisConnectionStrings").Value;
//实例名称
//options.InstanceName = "SampleInstance";
});"RedisConnectionStrings": "127.0.0.1:6379,password=,defaultDatabase=0,connectTimeout=5000,syncTimeout=1000" -
private readonly IDistributedCache _cache;
public ValuesController(IDistributedCache cache)
{
_cache = cache;
} -
var userid = _cache.GetString("userid");
if (userid==null)
{
//模拟读取数据库
userid = "abcd";
//设置缓存过期时间
var options = new DistributedCacheEntryOptions()
.SetSlidingExpiration(TimeSpan.FromSeconds(20));
_cache.SetString("userid", userid, options);
return Ok(userid);
}
else
{
return Ok(userid);
} -
官网:https://docs.microsoft.com/zh-cn/aspnet/core/performance/caching/distributed?view=aspnetcore-5.0

浙公网安备 33010602011771号