【问题标题】:Cache not refreshing when being called from a asynchrounous function in Spring从Spring中的异步函数调用时缓存不刷新
【发布时间】:2018-02-06 20:40:31
【问题描述】:

我正在调用一个带有CacheEvict 注释的函数。这是从一个本身异步执行的函数中调用的。

似乎在函数执行后缓存没有被驱逐。

这里是示例代码

@Async("executor1")
public void function1()
{
    // do something

    anotherFunction("name", 123, 12);

   // do something more

}

@CacheEvict(cacheNames = {"cache1", "cache2", "cache3"}, key = "#testId")
public List<Integer> anotherFunction(String name, int testId, int packageId)
{
  // some code here
}

我想要的是应该从所有缓存中清除与testId 对应的条目。 但是,在另一个通话中,我可以看到 cache1 的旧条目。正在从控制器调用function1。这两个功能都存在于服务中。现在,这个配置正确吗?如果是,缓存没有被清除的可能原因是什么?

任何帮助表示赞赏。提前致谢。

【问题讨论】:

    标签: caching asynchronous spring-boot ehcache spring-cache


    【解决方案1】:

    我认为您的问题是 Spring 代理不可重入。为了实现AsyncCacheEvict,Spring 创建了一个代理。因此,在您的示例中,调用堆栈将是:

    A -&gt; B$$proxy.function1() -&gt; B.function1() -&gt; B.anotherFunction()

    B$$proxy 包含异步和驱逐的逻辑。直接调用anotherFunction 时不适用。事实上,即使你删除了@Async,它仍然不起作用。

    您可以使用的一个技巧是将代理 bean 注入到类中。委托给类的代理而不是this

    public class MyClass {    
      private MyClass meWithAProxy;
    
      @Autowired
      ApplicationContext applicationContext;
    
      @PostConstruct
      public void init() {
        meWithAProxy = applicationContext.getBean(MyClass.class);
      }
    
      @Async("executor1")
      public void function1() {
        meWithAProxy.anotherFunction("name", 123, 12);
      }
    
      @CacheEvict(cacheNames = "cache1", key = "#testId")
      public List<Integer> anotherFunction(String name, int testId, int packageId) {
        return Collections.emptyList();
      }
    
    }
    

    它有效。但有一个问题。如果你现在直接打电话给anotherFunction,那就不行了。我认为这是一个 Spring 错误,并将按原样提交。

    【讨论】:

    • 我已经尝试过使用this,但没有成功。我不知道 this 与 bean 不同(我的错误)。所以现在,我现在已经删除了注释并正在使用 CacheManager 来驱逐所需的缓存。虽然我不确定它有多正确。
    • this 我的意思是注入代理。就像在我的代码示例中一样。这行得通。我试过了。
    猜你喜欢
    • 1970-01-01
    • 2015-01-22
    • 2010-09-20
    • 2020-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多