我正在使用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);
}
}
}
答案 0 :(得分:1)
您可以通过共享的私有方法在“删除/创建/编辑”上更新缓存的值:
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.AddMinutes(10);
var movies = await this.movieService.GetTopRatedMovies();
return movies;
});
model.Movies = cachedMovies;
return this.View(model);
}
[HttpPost]
public async Task<IActionResult> Delete(int id)
{
this.movieService.Delete(id);
UpdateCachedMovies();
return RedirectToAction(nameof(Index));
}
[HttpPost]
public async Task<IActionResult> Create(Movie model)
{
this.movieService.Add(model);
UpdateCachedMovies();
return RedirectToAction(nameof(Index));
}
private async void UpdateCachedMovies()
{
this.cacheService.Set("Movies", this.movieService.GetTopRatedMovies(), DateTime.UtcNow.AddMinutes(10));
}
}
}