我有一个具有多种方法的服务,我正在尝试使用 Spring @Cacheable
注释来缓存它们。一切正常,除了我发现没有缓存以数组作为方法参数的方法。考虑到数组可以保存不同的值,这在某种程度上是有道理的,但我仍然认为这是可能的。
缓存了以下方法:
@Cacheable("myCache")
public Collection<Building> findBuildingByCode(String buildingCode) {...}
@Cacheable("myCache")
public Collection<Building> getBuildings() {...}
但是,如果我将 findBuildingByCode
方法更改为以下任一方法,则它不会被缓存:
@Cacheable("myCache")
public Collection<Building> findBuildingByCode(String[] buildingCode) {...}
@Cacheable("myCache")
public Collection<Building> findBuildingByCode(String... buildingCode) {...}
这里是相关的Spring xml配置:
<!-- Cache beans -->
<cache:annotation-driven/>
<bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager"
p:cache-manager-ref="ehcache" />
<!-- EhCache library setup -->
<bean id="ehcache"
class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean" />
Ehcache配置:
<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
updateCheck="false">
<diskStore path="java.io.tmpdir/ehcache" />
<!-- Default settings -->
<defaultCache eternal="false" maxElementsInMemory="1"
overflowToDisk="false" diskPersistent="false" timeToIdleSeconds="0"
timeToLiveSeconds="100" memoryStoreEvictionPolicy="LRU" />
<!-- Other caches -->
<cache name="myCache" eternal="false" maxElementsInMemory="500"
overflowToDisk="false" diskPersistent="false" timeToIdleSeconds="0"
timeToLiveSeconds="43200" memoryStoreEvictionPolicy="LRU" />
</ehcache>
这是已知功能还是错误?
最佳答案
尝试像这样定义缓存键:
@Cacheable(value="myCache", key="#buildingCode.toString()")
或#buildingCode.hashCode()
。因此缓存管理器将能够缓存该方法。
关于java - 在 Spring 中缓存带有数组参数的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18001227/