简体   繁体   中英

How to set redis cache prefix key for non spring boot java application using xml configuration

I would like to set a custom cache key prefix for my application which uses xml configuration for my RedisCacheManager, my goal is, if the cache key is student-detail, the cache key should be test:: student-detail or prod:: student-detail, I have already set usePrefix to true, but I cant find a way to define the actual key value. Here below an extract of my cacheManager configuration.

<bean id="cacheManager" class="org.springframework.data.redis.cache.RedisCacheManager"
      c:redisOperations-ref="redisTemplate"
      c:defaultExpiration=3600
      c:usePrefix="true">
</bean>

For the information, I know in spring boot is as simple as setting a property in the application properties as:

spring.cache.redis.key-prefix=some::
spring.cache.redis.use-key-prefix=true

Just to put some context why I precised for non spring boot java application.

The solution is to create your custom redis cache prefix by implementing RedisCachePrefix.See the code below

package com.cache.custom.utils;

import com.morgan.design.properties.ReloadableProperty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.cache.RedisCachePrefix;
import org.springframework.data.redis.serializer.StringRedisSerializer;

public class MyRedisCachePrefix implements RedisCachePrefix {
/** The Prefix */
@ReloadableProperty("prefixString")
private String personalPrefixString;

/** The key string redis serializer */
@Autowired
String StringRedisSerializer stringRedisSerializer;

/** The delimiter */
private final String delimiter = "::";

@Override
public byte[] prefix(String cacheName) {
  return stringRedisSerializer.serialize(personalPrefixString.concat(":").concat(cacheName).concat(this.delimiter));
}
}

Then on the xml:

<bean id=stringRedisSerializer"
      class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
<bean id="redisCachePrefix"
      class="com.cache.custom.utils.MyRedisCachePrefix"/>
<bean id="cacheManager" class="org.springframework.data.redis.cache.RedisCacheManager"
      c:redisOperations-ref="redisTemplate"
      p:defaultExpiration=3600
      p:usePrefix="true"
      p:cachePrefix-ref="redisCachePrefix"
>
</bean>

NB: personalPrefixString value will be taken from properties files entry of prefixString. If prefixString value is testing and cacheName is student-details-cache then your cache key will be prefixed by: testing:student-details-cache::

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM