AspNetCore具有内置
memory cache
可用于存储请求之间共享的数据片段。
启动时注册缓存。。。
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddMemoryCache();
services.AddMvc();
}
public void Configure(IApplicationBuilder app)
{
app.UseMvcWithDefaultRoute();
}
}
你可以像这样注射它。。。
public class HomeController : Controller
{
private IMemoryCache _cache;
public HomeController(IMemoryCache memoryCache)
{
_cache = memoryCache;
}
public IActionResult Index()
{
string cultures = _cache[CacheKeys.Cultures] as CultureInfo[];
return View();
}
要使其在应用程序范围内工作,可以使用具有强类型成员的facade服务,并结合某种缓存刷新模式:
-
尝试从缓存中获取值
-
如果尝试失败
-
返回值
public CultureInfo[] Cultures { get { return GetCultures(); } }
private CultureInfo[] GetCultures()
{
CultureInfo[] result;
// Look for cache key.
if (!_cache.TryGetValue(CacheKeys.Cultures, out result))
{
// Key not in cache, so get data.
result = CultureInfo.GetCultures(CultureTypes.SpecificCultures);
// Set cache options.
var cacheEntryOptions = new MemoryCacheEntryOptions()
// Keep in cache for this time, reset time if accessed.
.SetSlidingExpiration(TimeSpan.FromMinutes(60));
// Save data in cache.
_cache.Set(CacheKeys.Cultures, result, cacheEntryOptions);
}
return result;
}
当然,您可以通过将其制作成一个服务来清理它,该服务将缓存作为一个依赖项接受,您可以在需要时将其注入到任何地方,但这是一般的想法。
注意还有一个
distributed cache
如果您想在web服务器之间共享数据。