开发喵星球

如何区分部署多个项目的Redis缓存(286)

如果部署了多个若依系统,连接的是同一个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加上对应的前缀。

   
分类:Java/OOP 作者:无限繁荣, 吴蓉 发表于:2024-07-31 10:01:46 阅读量:94
<<   >>


powered by kaifamiao