繁体   English   中英

在没有 Redis 的情况下在 Azure 上运行的 ASP.NET Core 应用程序中缓存数据

[英]Caching data in ASP.NET Core app running on Azure without Redis

我想在不依赖 Redis 的情况下缓存一些东西。 我的应用程序是在 Azure 应用服务上运行的 ASP.NET Core API 应用程序。

例如,我创建了一个国家列表

CultureInfo[] cultures = CultureInfo.GetCultures(CultureTypes.SpecificCultures);

我可以将它保存在 Redis 中,但它会花钱,而且这不是一个经常更改的列表,并且是从框架生成的,因此即使我正在运行我的 API 应用程序的多个实例,列表也将是相同的。

如何在没有 Redis 的情况下将其保存在内存中? 我可以调用一个在我的Startup.cs中生成这个列表的方法,但我在哪里存储它以及如何检索它?

AspNetCore 有一个内置的内存缓存,您可以使用它来存储请求之间共享的数据片段。

在启动时注册缓存...

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

为了使其在应用程序范围内工作,您可以使用具有强类型成员的外观服务并结合某种缓存刷新模式:

  1. 尝试从缓存中获取值
  2. 如果尝试失败
    • 从数据源中查找数据
    • 重新填充缓存
  3. 返回值

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

当然,您可以通过将其设置为接受缓存作为依赖项的服务来清理它,您可以将其注入到任何需要的地方,但这是一般的想法。

另请注意,如果您想在 Web 服务器之间共享数据,还有一个分布式缓存

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM