【问题标题】:Spring evict cache from method with another signatureSpring从具有另一个签名的方法中逐出缓存
【发布时间】:2021-04-02 07:23:48
【问题描述】:

我用一种方法缓存一些查询

    @Override
    @Cacheable(cacheNames = "user-actions")
    public UserAction getUserAction(UUID userId) {
        ...
    }

我想用另一种方法驱逐缓存。如果方法具有相同的签名,则它可以工作,例如

    @CacheEvict(cacheNames = "user-actions")
    public void evictUserLevel(UUID userId) {
        log.info("Cache user-actions has been evicted");
    }

但是,如果我不将userId 传递给将要驱逐缓存的方法,或者如果它有多个参数,有没有办法驱逐缓存?这不起作用:

    @CacheEvict(cacheNames = "user-actions")
    public void processEvent(UserEvent event, UUID userId) {
        ...
    }

【问题讨论】:

  • 指定方法参数用作缓存键(或将缓存设置为逐出所有)。

标签: java spring spring-cache


【解决方案1】:

这对我有用

    @CacheEvict(cacheNames = "user-events", key = "#root.args[1]")
    public void processEvent(UserEvent event, UUID userId) {
        ...
    }

root.args - 表示方法参数,[1] - 是参数的索引

【讨论】:

    【解决方案2】:

    引用documentation

    默认密钥生成

    由于缓存本质上是键值存储,因此缓存方法的每次调用都需要转换为适合缓存访问的键。开箱即用,缓存抽象使用基于以下算法的简单KeyGenerator

    • 如果没有给出参数,则返回 0。

    • 如果只给出一个参数,则返回该实例。

    • 如果给定多个参数,则返回根据所有参数的哈希计算的键。


    因此下面的签名不起作用,因为密钥是从 eventuserId 计算出来的。

    @CacheEvict(cacheNames = "user-actions")
    public void processEvent(UserEvent event, UUID userId) {
       ...
    }
    

    但是,如果我不将 userId 传递给将要驱逐缓存的方法,或者如果它有多个参数,是否有方法驱逐缓存?

    无参数

    设置allEntries=true,这将清除所有条目。

    @CacheEvict(cacheNames = "user-actions", allEntries = true)
    public void evictAll() {
    }
    

    对于多个参数

    key指定参数,详情参考Custom Key Generation Declaration

    @CacheEvict(cacheNames = "user-actions", key = "#userId")
    public void processEvent(UserEvent event, UUID userId) {
    ...
    }
    

    【讨论】:

      猜你喜欢
      • 2013-01-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-12
      • 2013-08-02
      • 1970-01-01
      • 2016-09-10
      • 2020-05-07
      相关资源
      最近更新 更多