SpringBoot RedisTemplate 操作不同的库

kyaa111 3年前 ⋅ 664 阅读

其他开发解决不了redis切换库, 于是通过消息队列, 让其他项目去操作对应的库, 太奇葩了, PM居然不管???

@Bean("redisTemplateForDb6")
public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory)  {
    RedisTemplate<Object, Object> template = new RedisTemplate<>();

    LettuceConnectionFactory lettuceConnectionFactory = (LettuceConnectionFactory) redisConnectionFactory;
    LettuceConnectionFactory lettuceConnectionFactoryNew =  new LettuceConnectionFactory(lettuceConnectionFactory.getStandaloneConfiguration());
    BeanUtil.copyProperties(lettuceConnectionFactory,lettuceConnectionFactoryNew, CopyOptions.create().setIgnoreNullValue(true));
    //指定切换的库
    lettuceConnectionFactoryNew.setDatabase(6);
    lettuceConnectionFactoryNew.afterPropertiesSet();
    template.setConnectionFactory(lettuceConnectionFactoryNew);

    // 使用Jackson2JsonRedisSerialize 替换默认序列化
    Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
    objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);

    jackson2JsonRedisSerializer.setObjectMapper(objectMapper);

    // 设置value的序列化规则和 key的序列化规则
    template.setKeySerializer(new StringRedisSerializer());
    template.setValueSerializer(jackson2JsonRedisSerializer);
    template.afterPropertiesSet();

    return template;
}