我在使用内存缓存时遇到问题(分别尝试了 IMemoryCache
和 IDistributedCache
以及 AddMemoryCache()
和 AddDistributedMemoryCache
)。看来缓存不在我的 ASP.NET Core 2.2 Web API 的端点之间共享,但它对于 1 个端点的请求是共享的。缓存被注入(inject)到单例服务的构造函数中。
这是我关心的问题:
- 请求转到端点 A,它调用 API,将响应存储到缓存并返回。
- 下一个请求将发送至端点 A,并且...成功获取缓存响应 - 正常。
- 但是当调用端点 B 时,我无法获得缓存响应(使用相同的 key )并且缓存似乎是空的
编辑:检查后我发现我确实为 API 的不同端点获得了另一个 MemoryCache
实例。
编辑#2:代码示例
DI:
services.AddDistributedMemoryCache();
services.AddSingleton<ICacheStore, CacheStore>();
services.AddScoped<CosmosDbUserRepository>();
services.AddScoped<IUserRepository>(sp =>
{
var realRepository = sp.GetRequiredService<CosmosDbUserRepository>();
var cache = sp.GetRequiredService<ICacheStore>();
return new CachedUserRepository(realRepository, cache);
});
缓存存储:
internal class CacheStore : ICacheStore
{
private static readonly JsonSerializer Serializer = new JsonSerializer();
private readonly IDistributedCache _cache;
public CacheStore(IDistributedCache cache)
{
_cache = cache ?? throw new ArgumentNullException(nameof(cache));
}
}
示例端点:
[HttpGet]
[ProducesResponseType(typeof(UserDetails), (int)HttpStatusCode.OK)]
public async Task<IActionResult> GetUserDetails(
[FromServices] QueryMediator mediator)
{
return Ok(
await mediator.HandleQuery<GetUserDetailsQuery, UserDetails>(null));
}
[HttpPatch("username")]
[ProducesResponseType((int)HttpStatusCode.NoContent)]
public async Task<IActionResult> ChangeUsername(
[FromBody] ChangeUsernameCommand command,
[FromServices] CommandMediator mediator)
{
await mediator.HandleCommand(command);
return NoContent();
}
最佳答案
问题已解决: 几个小时后,我尝试在启动时创建一个缓存实例并将特定实例注册为单例。有效!但现在我正在尝试用较小的应用程序重现该问题并为此创建一个问题:)代码如下:
var memoryCache = new MemoryDistributedCache(
Options.Create(new MemoryDistributedCacheOptions()));
services.AddSingleton<IDistributedCache>(memoryCache);
关于c# - Asp.Net Core Web Api 中端点之间的内存缓存似乎有所不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61718744/