ZHANGYONGHAO0 2020-06-16
.net core 使用Redis
安装包:Microsoft.Extensions.Caching.Redis
注册Redis(已经引用了Autofac)
public void ConfigureServices(IServiceCollection services)
{
// 这个是之前使用StackExchange.Redis时写的,可以共存
services.AddSingleton<IConnectionMultiplexer>(ConnectionMultiplexer.Connect(Configuration["Redis:Server"]));
// 这个是新加的
services.AddDistributedRedisCache(options => {
options.Configuration = Configuration["Redis:Server"]; //数据库配置的Redis连接字符串
options.InstanceName = Configuration["Redis:InstanceName"];//Redis实例名称
});
}
//使用Redis
using StackExchange.Redis;
public class TestRedis{
/// <summary>
/// Redis DB
/// </summary>
private readonly IDatabase _db;
/// <summary>
/// 分布式缓存
/// </summary>
private readonly IDistributedCache _cache;
public TestRedis(IConnectionMultiplexer redis, IDistributedCache cache, IHttpContextAccessor httpContextAccessor) {
this._db = redis.GetDatabase();
_cache = cache;
_httpContextAccessor = httpContextAccessor;
}
pulic void Write(string key,string value){
_cache.SetString(key, value, new DistributedCacheEntryOptions
{
AbsoluteExpirationRelativeToNow =
TimeSpan.FromMinutes(5))
});
}
public string Read(string key){
return _cache.GetString(key);
}
public string Remove(string key){
return _cache.Remove(key);
}
}