2

I am using spring cache with Redis for caching

I have the following methods:

    @CachePut(value ="DATA1", key = "#key1")
    public Object saveData1(long key1, Object obj) {
        return obj;
    }


    @CachePut(value ="DATA2", key = "#key1")
    public Object saveData2(long key1, Object obj) {
        return obj;
    }

This is causing collisions in keys and the data is being overridden.

I want to generate the key with the cache name appended to it.

Like: DATA1-key1, DATA2-key1.

Is it possible?

I have seen a few examples which use class name and method name. But I want to use the cache name.

Thank you.

Pardha.Saradhi
  • 468
  • 1
  • 10
  • 27
  • Possible duplicate of [Generating unique cache key with Spring KeyGenerator not working](http://stackoverflow.com/questions/27574786/generating-unique-cache-key-with-spring-keygenerator-not-working) – Bond - Java Bond Feb 27 '17 at 12:18

2 Answers2

4

Create a custom key generator like this:

@Component("myKeyGenerator")
public class MyKeyGenerator implements KeyGenerator {
    public Object generate(Object target, Method method, Object... params) {
        String[] value = new String[1];
        long key;
        CachePut cachePut = method.getAnnotation(CachePut.class);
        if (cachePut != null) {
            value = cachePut.value();
        }
        key = (long) params[0];
        return value[0] + "-" + key;
    }
}

And use it like below:

@CachePut(value = "DATA1", keyGenerator = "myKeyGenerator")

I haven't test this but should work, atleast you will get a basic idea how to do it.

Monzurul Shimul
  • 8,132
  • 2
  • 28
  • 42
1

You need to set parameter "usePrefix" as true in your CacheManager bean. This will prepend cacheName in your keys.

<bean id="cacheManager" class="org.springframework.data.redis.cache.RedisCacheManager">
    ...
     <property name="usePrefix"><value>true</value></property>
    ...
</bean>
arjunagarwal
  • 361
  • 1
  • 4
  • 17
  • This is in the redis docs: https://docs.spring.io/spring-data/data-redis/docs/1.0.5.RELEASE/api/org/springframework/data/redis/cache/RedisCacheManager.html – devo Nov 21 '19 at 01:24