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

标签 java spring ehcache spring-annotations

我有一个具有多种方法的服务,我正在尝试使用 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/

相关文章:

java - Apache POI - 如何将单元格值设置为日期格式?

Java Spring 错误 : It is not working even i đid exactly everything the teacher said

mysql - NoSQL 或 Ehcache 缓存?

java - 为什么不抽象字段?

java - 通过 https 的 SonarQube

java - 是否可以在 AuditorAwareImpl 类中使用存储库?

java - DiskStore开启时Ehcache复制?

java - 如何以编程方式更改 EhCache 成员的到期时间

java - Dagger 2 未注入(inject)接口(interface)类型

java - 通过 Spring 集成从分页 REST 服务读取和下载