【发布时间】:2017-08-18 15:47:30
【问题描述】:
我在更新项目后尝试刷新缓存,我尝试了几个不同的选项,但没有一个按预期工作
public class PostApiController : Controller
{
private readonly IPostService _postService;
private readonly IPostTagService _postTagService;
private IMemoryCache _cache;
private MemoryCacheEntryOptions cacheEntryOptions;
public PostApiController(IPostService postService, IPostTagService postTagService, IMemoryCache cache)
{
_postService = postService;
_postTagService = postTagService;
_cache = cache;
cacheEntryOptions = new MemoryCacheEntryOptions()
.SetSlidingExpiration(TimeSpan.FromDays(1));
}
[HttpGet("{url}", Name = "GetPost")]
public IActionResult GetById(string url, bool includeExcerpt)
{
Post cacheEntry;
if (!_cache.TryGetValue($"GetById{url}{includeExcerpt}", out cacheEntry))
{
cacheEntry = _postService.GetByUrl(url, includeExcerpt);
_cache.Set($"GetById{url}{includeExcerpt}", cacheEntry, cacheEntryOptions);
}
if (cacheEntry == null)
{
return NotFound();
}
return new ObjectResult(cacheEntry);
}
[HttpPut("{id}")]
public IActionResult Update(int id, [FromBody] Post item)
{
if (item == null)
{
return BadRequest();
}
var todo = _postService.GetById(id);
if (todo == null)
{
return NotFound();
}
_postService.Update(item);
_postTagService.Sync(item.Tags.Select(a => new PostTag { PostId = item.Id, TagId = a.Id }).ToList());
//Want to flush entire cache here
return new NoContentResult();
}
我已尝试在这里 Dispose() MemoryCache 但在下一次 Api 调用时,它仍然被释放。由于钥匙有点动态,我不能只拿到钥匙。我该怎么做?
【问题讨论】:
-
为什么叫它GetById而不是GetByUrl?
-
不管怎样,你能重构Update方法中的GetById{url}部分吗?
-
确定
todo项目具有Url属性,您可以使用该属性重新将该项目重新插入缓存?或者甚至删除includeExcerpttrue 和 false 变体?
标签: c# .net-core memorycache