如果部署了多个若依系统,连接的是同一个
Redis
源时会导致Key
值冲突,我们可以修改Redis
默认的序列化值用于区分。
1、新增RedisKeySerializer.java
序列化,添加Key
前缀值。
@Component
public class RedisKeySerializer implements RedisSerializer<String>
{
@Autowired
private RuoYiConfig config;
private final Charset charset;
public RedisKeySerializer()
{
this(Charset.forName("UTF8"));
}
public RedisKeySerializer(Charset charset)
{
Assert.notNull(charset, "字符集不允许为NULL");
this.charset = charset;
}
@Override
public byte[] serialize(String string) throws SerializationException
{
// 通过项目名称ruoyi.name来定义Redis前缀,用于区分项目缓存
if (StringUtils.isNotEmpty(config.getName()))
{
return new StringBuilder(config.getName()).append(":").append(string).toString().getBytes(charset);
}
return string.getBytes(charset);
}
@Override
public String deserialize(byte[] bytes) throws SerializationException
{
return (bytes == null ? null : new String(bytes, charset));
}
}
2、修改RedisConfig.java
,配置新的RedisKeySerializer
。
@Bean
@SuppressWarnings(value = { "unchecked", "rawtypes" })
public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory, RedisKeySerializer redisKeySerializer)
{
....
// 使用StringRedisSerializer来序列化和反序列化redis的key值
template.setKeySerializer(redisKeySerializer);
template.setValueSerializer(serializer);
// Hash的key也采用StringRedisSerializer的序列化方式
template.setHashKeySerializer(redisKeySerializer);
template.setHashValueSerializer(serializer);
template.afterPropertiesSet();
return template;
}
3、修改CacheController.java
,添加缓存Key
前缀。
public static final String REDIS_NAME = "RuoYi:";
private final static List<SysCache> caches = new ArrayList<SysCache>();
{
caches.add(new SysCache(REDIS_NAME + CacheConstants.LOGIN_TOKEN_KEY, "用户信息"));
caches.add(new SysCache(REDIS_NAME + CacheConstants.SYS_CONFIG_KEY, "配置信息"));
caches.add(new SysCache(REDIS_NAME + CacheConstants.SYS_DICT_KEY, "数据字典"));
caches.add(new SysCache(REDIS_NAME + CacheConstants.CAPTCHA_CODE_KEY, "验证码"));
caches.add(new SysCache(REDIS_NAME + CacheConstants.REPEAT_SUBMIT_KEY, "防重提交"));
caches.add(new SysCache(REDIS_NAME + CacheConstants.RATE_LIMIT_KEY, "限流处理"));
caches.add(new SysCache(REDIS_NAME + CacheConstants.PWD_ERR_CNT_KEY, "密码错误次数"));
}
此时自定义配置application.yml
中的ruoyi.name
就会把所有redis key
加上对应的前缀。
powered by kaifamiao