Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Caching in Spring on methods with array parameters

I have a service with multiple methods and am attempting to cache them using Spring @Cacheable annotations. Everything works fine except I've found the methods with an array as a method parameter are not cached. This somewhat makes sense considering arrays can hold different values, but I would still think it would be possible.

The following methods are cached:

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

@Cacheable("myCache")
public Collection<Building> getBuildings() {...}

However, if I change the findBuildingByCode method to either of the following, it is not cached:

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

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

Here is the relevant Spring xml configuration:

<!-- 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 configuration:

<?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>

Is this known functionality or a bug?

like image 313
acvcu Avatar asked Sep 06 '26 02:09

acvcu


1 Answers

Try to define the cache key like that:

@Cacheable(value="myCache", key="#buildingCode.toString()")

Or #buildingCode.hashCode(). So the cache manager will be able to cache the method.

like image 191
Benoit Wickramarachi Avatar answered Sep 07 '26 15:09

Benoit Wickramarachi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!