RsCode中提供了内存缓存,memcached缓存,redis缓存
只需两步完成对缓存的调用:
1.缓存注册
2.缓存调用
第一步:缓存注册
任选其一,或者都使用
1.1 内存缓存注册
csharp
services.AddMemoryCaches();
1.2 redis缓存注册
appsetting.json 中 节点RedisServer:Server 设置为 redis的连接
json
"RedisServer": {
"Server": "127.0.0.1:6379,password=1,defaultDatabase=db0"
}
方式一:
csharp
services.AddRedisCaches(Configuration);
方式二:
csharp
string connStr=Configuration.GetValue<string>("RedisServer:Server");
services.AddRedisCaches(Configuration,connStr);
1.3 memcache缓存注册
appsettings.json中 memcached的配置
json
{
"enyimMemcached": {
"Servers": [
{
"Address": "memcached",
"Port": 11211
}
],
"Authentication": {
"Type": "Enyim.Caching.Memcached.PlainTextAuthenticator",
"Parameters": {
"zone": "",
"userName": "username",
"password": "password"
}
}
}
}
Startup中的配置
csharp
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddEnyimMemcached(options => Configuration.GetSection("enyimMemcached").Bind(options));
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.UseEnyimMemcached();
}
}
第二步:缓存调用
1.2调用 注入IEnumerable<ICacheProvider>
后,调用,例:
csharp
IEnumerable<ICacheProvider> caches;
public HomeController(IEnumerable<ICacheProvider> _caches)
{
caches=_caches;
}
public ActionResult Index()
{
var cache= caches.FirstOfDefault(c=>c.CacheName=="memory");
cache.Set("key","xx"); //默认缓存300秒
//cache.Set("key","xx",3000); //缓存数据3000秒
//cache.Set("key","xx",DateTime.Now.AddDay(1)); //缓存数据一天
cache.Get("xx");
}
CacheName的值,表示:
memory 内存缓存
redis redis缓存
memcached memcached缓存