gpt4 book ai didi

c# - 刷新内存缓存 ASP.NET Core 2

转载 作者:太空宇宙 更新时间:2023-11-03 15:02:04 30 4
gpt4 key购买 nike

我在更新项目后尝试刷新缓存,我尝试了几个不同的选项,但没有一个按预期工作

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 调用时,它仍会被释放。由于 key 有些动态,我不能只获取 key 。我该怎么做呢?

最佳答案

您可以改为存储字典。通过这种方式,您可以为条目使用动态键,为字典容器使用一个静态键,它可以存储在缓存中,而不是单独存储每个条目。

类似的东西:

private const string CachedEntriesKey = "SOME-STATIC-KEY";

[HttpGet("{url}", Name = "GetPost")]
public IActionResult GetById(string url, bool includeExcerpt)
{
Dictionary<string, Post> cacheEntries;
if (!_cache.TryGetValue(CachedEntriesKey, out cacheEntries))
{
cacheEntries = new Dictionary<string, Post>();
_cache.Set(CachedEntriesKey, cacheEntries);
}

var entryKey = $"GetById{url}{includeExcerpt}";
if (!cacheEntries.ContainsKey(entryKey))
{
return NotFound(); // by the way, why you do that instead of adding to the cache?
}

return new ObjectResult(cacheEntries[entryKey]);
}

关于c# - 刷新内存缓存 ASP.NET Core 2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45760521/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com