RsCode中提供了内存缓存,memcached缓存,redis缓存

安装 RsCode.AspNetCore

PM> Install-Package RsCode.AspNetCore -Version 1.4.2

只需两步完成对缓存的调用:

1.缓存注册

2.缓存调用

第一步:缓存注册

任选其一,或者都使用

1.1内存缓存注册

services.AddMemoryCaches();

1.2 redis缓存注册 appsetting.json 中 节点RedisServer:Server 设置为 redis的连接

"RedisServer": {
    "Server": "127.0.0.1:6379,password=1,defaultDatabase=db0"
  }

方式一:

services.AddRedisCaches(Configuration);

方式二:

string connStr=Configuration.GetValue<string>("RedisServer:Server");
services.AddRedisCaches(Configuration,connStr);

1.3 memcache缓存注册

appsettings.json中 memcached的配置
{
  "enyimMemcached": {
    "Servers": [
      {
        "Address": "memcached",
        "Port": 11211
      }
    ],
    "Authentication": {
      "Type": "Enyim.Caching.Memcached.PlainTextAuthenticator",
      "Parameters": {
        "zone": "",
        "userName": "username",
        "password": "password"
      }
    }
  }
}


Startup中的配置
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 后,调用,例:

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缓存

results matching ""

    No results matching ""