我在网上到处寻找上述问题的简单答案,但找不到。我有一个类似的方法:
@Cacheable(cacheNames = "objects")
public List<Object> get() { .. }
我将 EhCache 2.10.0 与 Spring Framework 4.2.1 一起使用,我可以看到此方法的以下输出:
Adding cacheable method 'get' with attribute: [CacheableOperation[public java.util.List com.example.DAO.get()] caches=[objects] | key='' ...
也(在以后的日志中)
Computed cache key 'SimpleKey []' for operation ...
@Cacheable 注解应该在这种情况下做什么?将每个对象放在由 hashCode 键入的缓存中(如其他地方所暗示的那样)?或者只是将整个列表按原样放入某个基于列表的 hashCode 下的缓存中?
最佳答案
Spring Doc 提到了这一点:
Since caches are essentially key-value stores, each invocation of a cached method needs to be translated into a suitable key for cache access. Out of the box, the caching abstraction uses a simple KeyGenerator based on the following algorithm:
If no params are given, return
SimpleKey.EMPTY
If only one param is given, return that instance
If more the one param is given, return a key computed from the hashes of all parameters.
https://docs.spring.io/spring/docs/5.0.8.RELEASE/spring-framework-reference/integration.html#cache
当您使用 @Cacheable(cacheNames = "objects")
对其进行注释时你给它一个缓存名称,它可以根据它来识别缓存。由于您的方法没有任何参数,因此将 cacheName 作为“对象”,它已经缓存了返回对象(在本例中为 List<Object>
)。并且每次调用该方法时,它都会使用 cacheName 对象和键值为 '0' 来检查缓存。如果它已经有一个之前缓存的返回对象,它将返回该对象。
更新:与 SimpleKey.EMPTY
Spring 4+ 没有参数的关键
关于java - Spring 的 @Cacheable 放在返回列表的方法上时会做什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32624565/