繁体   English   中英

Memory 缓存似乎在 Asp.Net Core Web Api 中的端点之间有所不同

[英]Memory cache seems to differ between endpoints in Asp.Net Core Web Api

我在使用 memory 缓存时遇到问题(分别尝试了IMemoryCacheIDistributedCacheAddMemoryCache()AddDistributedMemoryCache )。 我的 asp.net 核心 2.2 web api 的端点之间似乎没有共享缓存,但它是为 1 个端点的请求共享的。 缓存被注入到 singleton 服务的构造函数中。

这是我关心的问题:
1)向端点A请求go,它调用API,将响应存储到缓存并返回。
2)下一个请求 go 端点 A 和...成功获得缓存响应 - 好的。
3)但是当调用一个端点 B 时,我无法获得缓存响应(使用相同的键)并且缓存似乎是空的

编辑:检查后我发现我确实为我的 API 的不同端点获得了另一个 MemoryCache 实例。

EDIT2:代码示例 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();
        }

问题已解决:数小时后,我尝试在启动时创建缓存实例并将特定实例注册为 Singleton。 它有效:但现在我正在尝试用较小的应用程序重现该问题并为此创建一个问题:) 下面的代码:

            var memoryCache = new MemoryDistributedCache(
                Options.Create(new MemoryDistributedCacheOptions()));
            services.AddSingleton<IDistributedCache>(memoryCache);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM