【发布时间】:2019-05-02 23:47:13
【问题描述】:
我正在使用 IMemoryCache 并运行一个 asp-net 核心项目。在主页上,我列出了一些电影,它们被缓存了大约 10 分钟。有没有办法更新缓存,如果电影已经创建/删除/编辑,如果那 10 分钟还没有过去?
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;
using MovieManagement.Models;
using MovieManagement.Models.Home;
using MovieManagement.Services.Contracts;
using MovieManagement.ViewModels;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading.Tasks;
namespace MovieManagement.Controllers
{
public class HomeController : Controller
{
private readonly IMovieService movieService;
private readonly IMemoryCache cacheService;
public HomeController(IMovieService movieService, IMemoryCache cache)
{
this.movieService = movieService ?? throw new ArgumentNullException(nameof(movieService));
this.cacheService = cache ?? throw new ArgumentNullException(nameof(cache));
}
public async Task<IActionResult> Index()
{
var model = new HomeIndexViewModel();
var cachedMovies = await this.cacheService.GetOrCreateAsync("Movies", async entry =>
{
entry.AbsoluteExpiration = DateTime.UtcNow.AddSeconds(20);
var movies = await this.movieService.GetTopRatedMovies();
return movies;
});
model.Movies = cachedMovies;
return this.View(model);
}
}
}
【问题讨论】:
-
你看过这个 SO 问题吗:stackoverflow.com/questions/48743516/…
-
是的,我有,但对我的情况没有帮助,谢谢。
标签: caching asp.net-core browser-cache memorycache