RedisTemplate操作细节和多库操作.

Scroll Down

直接看代码:

package com.dm.td.core.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.Profile;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * @author wajn
 * reids 相关bean的配置
 */
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {


    /**
     * 获取2库的redis
     *
     * @param factory
     * @return
     */
    @Bean("authRedisTemplate")
    @Profile({"dev", "test"})
    public RedisTemplate<String, String> authRedisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, String> template = new RedisTemplate<>();

        LettuceConnectionFactory connectionFactory = new LettuceConnectionFactory();
        BeanUtils.copyProperties(factory, connectionFactory);
        connectionFactory.setDatabase(2);
        connectionFactory.afterPropertiesSet();
        connectionFactory.resetConnection();
        template.setConnectionFactory(connectionFactory);
        Jackson2JsonRedisSerializer jacksonSeial = getJackson2JsonRedisSerializer();

        // 值采用json序列化
        template.setValueSerializer(jacksonSeial);
        //使用StringRedisSerializer来序列化和反序列化redis的key值
        template.setKeySerializer(new StringRedisSerializer());

        // 设置hash key 和value序列化模式
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(jacksonSeial);
        template.afterPropertiesSet();
        return template;
    }

    private Jackson2JsonRedisSerializer getJackson2JsonRedisSerializer() {
        // 配置连接工厂
        //使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值(默认使用JDK的序列化方式)
        Jackson2JsonRedisSerializer jacksonSeial = new Jackson2JsonRedisSerializer(Object.class);

        ObjectMapper om = new ObjectMapper();
        // 指定要序列化的域,field,get和set,以及修饰符范围,ANY是都有包括private和public
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        // 指定序列化输入的类型,类必须是非final修饰的,final修饰的类,比如String,Integer等会跑出异常
//        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jacksonSeial.setObjectMapper(om);
        return jacksonSeial;
    }


    /**
     * retemplate相关配置
     *
     * @param factory
     * @return
     */
    @Bean
    @Primary
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        // 配置连接工厂
        template.setConnectionFactory(factory);

        //使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值(默认使用JDK的序列化方式)
        Jackson2JsonRedisSerializer jacksonSeial = getJackson2JsonRedisSerializer();

        // 值采用json序列化
        template.setValueSerializer(jacksonSeial);
        //使用StringRedisSerializer来序列化和反序列化redis的key值
        template.setKeySerializer(new StringRedisSerializer());

        // 设置hash key 和value序列化模式
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(jacksonSeial);
        template.afterPropertiesSet();
        return template;
    }
}

需要注意:

如果直接在代码中切换选库. 则会更改所有的RedisTemplat的ConnectionFactory属性.

所有authRedisTemplate 直接copy了一份RedisConnectionFactory的副本. 否则的话会全部修改RedisConnectionFactory对象.

	connectionFactory.setDatabase(2);

	//非常重要,网上好多博客都没有这步.都是错的.
        connectionFactory.afterPropertiesSet();
        connectionFactory.resetConnection();

如果自己自定义封装RedisTemplate 可以参考authRedisTemplate的Bean.

备注: 在注入authRedisTemplate对象时. 请不要加泛型,错误示例:

    @Autowired(required = false)
    @Qualifier("authRedisTemplate")
//如果加了泛型, 默认会找 StringRedisTemplate Bean. 而默认的StringRedisTemplate没有配置自定的2库<authRedisTemplate bean>.
    private RedisTemplate<String,String> authRedisTemplate;


// 正确用法:
    @Autowired(required = false)
    @Qualifier("authRedisTemplate")
    private RedisTemplate authRedisTemplate;