在 Spring 中缓存带有数组参数的方法

acv*_*vcu 3 java spring ehcache spring-annotations

我有一个具有多种方法的服务,并尝试使用 Spring@Cacheable注释来缓存它们。一切正常,除非我发现带有数组作为方法参数的方法没有被缓存。考虑到数组可以保存不同的值,这有点有意义,但我仍然认为这是可能的。

缓存了以下方法:

@Cacheable("myCache")
public Collection<Building> findBuildingByCode(String buildingCode) {...}

@Cacheable("myCache")
public Collection<Building> getBuildings() {...}
Run Code Online (Sandbox Code Playgroud)

但是,如果我将findBuildingByCode方法更改为以下任一方法,则不会缓存它:

@Cacheable("myCache") 
public Collection<Building> findBuildingByCode(String[] buildingCode) {...}

@Cacheable("myCache")
public Collection<Building> findBuildingByCode(String... buildingCode) {...}
Run Code Online (Sandbox Code Playgroud)

这是相关的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" />
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

这是已知的功能还是错误?

Ben*_*chi 6

尝试像这样定义缓存键:

@Cacheable(value="myCache", key="#buildingCode.toString()")
Run Code Online (Sandbox Code Playgroud)

或者#buildingCode.hashCode()。因此缓存管理器将能够缓存该方法。

  • 像arrayList hashMap 这样的集合怎么样? (2认同)