代码之家  ›  专栏  ›  技术社区  ›  treze

Polly缓存策略没有向缓存添加值

  •  0
  • treze  · 技术社区  · 7 年前

    我无法使用Polly项目的缓存策略。 我已经根据这些例子进行了设置,基本上看起来是可行的。

    我已经编写了一个单元测试,在这个测试中,值被成功地检索、放入缓存并在以后的调用中从缓存中读取。 但是,当我在asp.net核心上下文中运行代码时,它并没有按预期工作。执行包装的操作并检索值。但是,put to cache方法永远不会执行。 我试着用我自己的IAsyncCacheProvider来调试这个问题。它的PutAsync方法永远不会在asp.net上下文中调用。但是,当在单元测试中运行时,它被调用。

    这里是我的服务配置

    services.AddSingleton<IAsyncCacheProvider, MemoryCacheProvider>();
    services.AddSingleton<IPolicyRegistry<string>, PolicyRegistry>();
    

    这里是引起这些问题的课堂摘录。

    public Bar(
                IPolicyRegistry<string> policyRegistry,
                IService service,
                IAsyncCacheProvider cacheProvider)
    {
         this.policyRegistry = policyRegistry;
         this.service = service;
         this.cacheProvider = cacheProvider;
    }
    
     public Task<bool> Foo(Guid id)
     {
        var cachePolicy = this.GetPolicy();
    
        return cachePolicy.ExecuteAsync(
               _ => this.service.Foo(id),
               new Context("policyKey" + id));
     }
    
    
    private CachePolicy<bool> GetPolicy()
    {
        if(!this.policyRegistry.TryGet(PolicyKey, out CachePolicy<bool> policy))
        {
             policy = Policy.CacheAsync<bool>(
             this.cacheProvider.AsyncFor<bool>(),
             TimeSpan.FromMinutes(5),
             (c, s) => { },
             (c, s) => { },
             (c, s) => { },
             (c, s, e) => { },
             (c, s, e) => { });
    
             this.policyRegistry.Add(PolicyKey, policy);
       }
    
       return policy;
    }
    

    有什么想法,是什么导致了这种行为?当我放置断点时,它从不尝试将返回值添加到缓存中。也没有例外。

    1 回复  |  直到 7 年前
        1
  •  1
  •   treze    7 年前

    在CacheEngine类中有以下代码。

    if (ttl.Timespan > TimeSpan.Zero && result != null && !result.Equals(default(TResult)))
      {
      try
      {
          await cacheProvider.PutAsync(cacheKey, result, ttl, cancellationToken, continueOnCapturedContext).ConfigureAwait(continueOnCapturedContext);
          onCachePut(context, cacheKey);
      }
      catch (Exception ex)
      {
           onCachePutError(context, cacheKey, ex);
      }
    }
    

    因此,每当这个服务的返回值bool碰巧为false时,就不会将其放入缓存,因为这实际上是该类型的默认值。在单元测试中,我碰巧使用true作为返回值,因此缓存工作。