.net core Redis

2021-02-04 11:17

阅读:554

标签:str   extension   使用   figure   return   name   summary   relative   nec   

.net core 使用Redis

安装包:Microsoft.Extensions.Caching.Redis

 

注册Redis(已经引用了Autofac)

 public void ConfigureServices(IServiceCollection services)

{

 

// 这个是之前使用StackExchange.Redis时写的,可以共存
services.AddSingleton(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{


///


/// Redis DB
///

private readonly IDatabase _db;
///
/// 分布式缓存
///

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);

}

 

}

.net core Redis

标签:str   extension   使用   figure   return   name   summary   relative   nec   

原文地址:https://www.cnblogs.com/ruiying/p/13140196.html


评论


亲,登录后才可以留言!