@Cacheable key on multiple method arguments

后端 未结 6 2042
粉色の甜心
粉色の甜心 2020-11-30 18:36

From the spring documentation :

@Cacheable(value=\"bookCache\", key=\"isbn\")
public Book findBook(ISBN isbn, boolean checkWarehouse, boolean includeUsed)
         


        
6条回答
  •  醉话见心
    2020-11-30 18:49

    After some limited testing with Spring 3.2, it seems one can use a SpEL list: {..., ..., ...}. This can also include null values. Spring passes the list as the key to the actual cache implementation. When using Ehcache, such will at some point invoke List#hashCode(), which takes all its items into account. (I am not sure if Ehcache only relies on the hash code.)

    I use this for a shared cache, in which I include the method name in the key as well, which the Spring default key generator does not include. This way I can easily wipe the (single) cache, without (too much...) risking matching keys for different methods. Like:

    @Cacheable(value="bookCache", 
      key="{ #root.methodName, #isbn?.id, #checkWarehouse }")
    public Book findBook(ISBN isbn, boolean checkWarehouse) 
    ...
    
    @Cacheable(value="bookCache", 
      key="{ #root.methodName, #asin, #checkWarehouse }")
    public Book findBookByAmazonId(String asin, boolean checkWarehouse)
    ...
    

    Of course, if many methods need this and you're always using all parameters for your key, then one can also define a custom key generator that includes the class and method name:

    
    
    

    ...with:

    public class CacheKeyGenerator 
      implements org.springframework.cache.interceptor.KeyGenerator {
    
        @Override
        public Object generate(final Object target, final Method method, 
          final Object... params) {
    
            final List key = new ArrayList<>();
            key.add(method.getDeclaringClass().getName());
            key.add(method.getName());
    
            for (final Object o : params) {
                key.add(o);
            }
            return key;
        }
    }
    
        

    提交回复
    热议问题