Spring @Cacheable with complex keys still executed

前端 未结 2 954
醉酒成梦
醉酒成梦 2021-01-01 00:11

I have the following for the usage of a @Cacheable in spring (3.1):

spring:




        
相关标签:
2条回答
  • 2021-01-01 00:47

    The key does not appear correct -

    You may have meant - @Cacheable(value="cacheName", key="#param1.concat(‘-’).concat(#param2)")

    Further, if the compilation is done without debug information, the param1, param2 argument names will not be available to expression evaluator. Instead you can refer to them using p0, p1 etc this way:

    @Cacheable(value="cahceName", key="#p0.concat('-').concat(#p1)")

    Update:

    I have a one page test here which demonstrates how this works - https://gist.github.com/3315275

    0 讨论(0)
  • 2021-01-01 01:02

    In my case, the problem was caused by using the wrong configuration of the cache provider (Caffeine):

    @Bean
    public Caffeine<Object, Object> caffeineCacheBuilder() {
        return Caffeine.newBuilder()
            .initialCapacity(100)
            .maximumSize(1000)
            .expireAfterAccess(10, TimeUnit.MINUTES)
            .weakKeys(); // cause problems when concatenated keys used
    }
    

    As the docs says, weakKeys() method:

    Specifies that each key (not value) stored in the cache should be wrapped in a WeakReference (by default, strong references are used).

    Warning: when this method is used, the resulting cache will use identity ({@code ==}) comparison to determine equality of keys. Its {@link Cache#asMap} view will therefore technically violate the {@link Map} specification (in the same way that {@link IdentityHashMap} does).

    0 讨论(0)
提交回复
热议问题