services.AddStackExchangeRedisCache(options =>
{
options.Configuration = "localhost";
options.InstanceName = "SampleInstance";
});
其中,options.Configuration 值为 Redis 服务器地址,options.InstanceName 值为缓存实例名称。
public class HomeController : Controller
{
private readonly IDistributedCache _cache;
public HomeController(IDistributedCache cache)
{
_cache = cache;
}
public async Task Index()
{
string cacheKey = "sample_key";
string cachedResponse = await _cache.GetStringAsync(cacheKey);
if (cachedResponse != null)
{
return Content(cachedResponse);
}
string response = "Hello, world!";
await _cache.SetStringAsync(cacheKey, response);
return Content(response);
}
}
public void ConfigureServices(IServiceCollection services)
{
..
services.AddStackExchangeRedisCache(options =>
{
options.Configuration = "localhost";
options.InstanceName = "SampleInstance";
});
services.AddMvc();
..
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
..
app.UseStaticFiles();
app.UseMvc();
}
至此,ASP.NET Core 应用程序中的内存缓存已经被替换为 RedisCache。