Reputation: 478
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.
Upvotes: 2
Views: 4582
Reputation: 391
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>
Upvotes: 1
Reputation: 8396
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.
Upvotes: 4