c# - 如何在缓存中存储数据?

标签 c# asp.net asp.net-core asp.net-core-mvc

我创建了一个 ViewComponent显示 List<Product> ,该列表是从 REST API 中获取的数据。服务,这是我的类实现:

public class ProductsViewComponent : ViewComponent
{
    private readonly HttpClient _client;

    public ProductsViewComponent(HttpClient client)
    {
        _client = client ?? throw new ArgumentNullException(nameof(client));
    }

    public async Task<IViewComponentResult> InvokeAsync(string date)
    {
       using (var response = await _client.GetAsync($"/"product/get_products/{date}"))
       {
           response.EnsureSuccessStatusCode();
           var products = await response.Content.ReadAsAsync<List<Product>>();
           return View(products);
       }
    }
}

我在 Components 中可用的 html 表中加载列表文件夹:Views\Shared\Components\Products\Default.cshtml .

在每个View需要显示 Products我做了:

@await Component.InvokeAsync("Products", new { date = myDate })

REST API使用 HttpClient 调用在 Startup.cs 中配置如下:

services.AddHttpClient<ProductsViewComponent>(c =>
{
    c.BaseAddress = new Uri('https://api.myservice.com');
});

这很好用,但主要问题是每次用户重新加载页面或可能进入另一个需要显示产品列表的 View 时,应用程序将生成另一个 API打电话。

是否可以将列表存储在缓存之类的东西中并防止调用 API如果日期等于之前选择的日期,是否再次?

我在学习ASP.NET Core所以我不是这个论点的专家。

在此先感谢您的帮助。

最佳答案

根据微软文档 https://learn.microsoft.com/en-us/aspnet/core/performance/caching/memory?view=aspnetcore-2.1

你可以使用IMemoryCache来缓存数据

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMemoryCache();

         services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
    }

    public void Configure(IApplicationBuilder app)
    {
        app.UseMvcWithDefaultRoute();
    }
}

并创建 IMemoryCache 的实例。这是 Microsoft 文档中的示例。您可以创建另一个类来一起处理这一切,在下面的示例中,这只是保存 DateTime 但是,您可以将任何对象保存在缓存中,当您尝试从缓存中读取该值时,只需要将该对象转换为类型。

我强烈建议您阅读上述文档。

public class HomeController : Controller
{
    private IMemoryCache _cache;

    public HomeController(IMemoryCache memoryCache)
    {
        _cache = memoryCache;
    }

    public IActionResult CacheTryGetValueSet()
    {
       DateTime cacheEntry;

       // Look for cache key.
       if (!_cache.TryGetValue(CacheKeys.Entry, out cacheEntry))
       {
           // Key not in cache, so get data.
           cacheEntry = DateTime.Now;

           // Set cache options.
           var cacheEntryOptions = new MemoryCacheEntryOptions()
           // Keep in cache for this time, reset time if accessed.
                .SetSlidingExpiration(TimeSpan.FromSeconds(3));

           // Save data in cache.
        _cache.Set(CacheKeys.Entry, cacheEntry, cacheEntryOptions);
      }

      return View("Cache", cacheEntry);
   }

}

更新:CacheKeys.Entry 是一个静态类,其中定义了所有键。 (只是编码标准)。请检查上面的文档链接。

public static class CacheKeys
{
   public static string Entry { get { return "_Entry"; } }
   public static string CallbackEntry { get { return "_Callback"; } }
   public static string CallbackMessage { get { return "_CallbackMessage"; } }
   public static string Parent { get { return "_Parent"; } }
   public static string Child { get { return "_Child"; } }
   public static string DependentMessage { get { return "_DependentMessage";} }
   public static string DependentCTS { get { return "_DependentCTS"; } }
   public static string Ticks { get { return "_Ticks"; } }
   public static string CancelMsg { get { return "_CancelMsg"; } }
   public static string CancelTokenSource { get { return "_CancelTokenSource";} }   
}

关于c# - 如何在缓存中存储数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52221195/

相关文章:

c# - 监视进程的网络使用情况?

c# - 避免非只读静态字段 - Immutability NDepend

c# - 如何使用 JQuery Ajax 调用从 Web 方法发送和检索数据?

c# - Swashbuckle - 返回响应的 Swagger 的文档?

c# - 如何在 C# 中将 Int64 转换为十六进制以及从十六进制转换为字节

c# - 无法在 Visual Studio 中构建 C# 项目

c# - "Nullable object must have a value"在非原始/非结构对象上检查 null 后出现异常

使用 MySQL 的 ASP.NET 4.5 OAuth

c# - ASP.NET Core 省略了 SameSite Cookie 属性

asp.net - 在 ASP.NET Core MVC 的操作级别压缩过滤器