SpringBoot配置RedisTemplate

1、导入Maven依赖

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>

2、配置连接信息

spring.redis.host=172.30.3.157
spring.redis.port=6379
spring.redis.password=

3、配置Config 配置类,修改序列化方式,实体类需要实现 java.io.Serializable 接口

@Configuration
public class RedisConfig {

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

        template.setConnectionFactory(redisConnectionFactory);

        //配置序列化方式
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);

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

        jackson2JsonRedisSerializer.setObjectMapper(obm);

        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        //key 采用String的序列化方式
        template.setKeySerializer(stringRedisSerializer);
        //hash
        template.setHashKeySerializer(stringRedisSerializer);
        //value
        template.setValueSerializer(jackson2JsonRedisSerializer);
        template.afterPropertiesSet();
        return template;
    }

}

说明:

自动配置类
org.springframework.boot.autoconfigure.data.redis.RedisProperties
org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration
默认连接工厂
org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory

4、在需要使用的地方注入ReidsTemplate

    @Autowired
    RedisTemplate redisTemplate;

5、使用说明

    redisTemplate.opsForValue() 操作String
    redisTemplate.opsForList()  操作LIST
    redisTemplate.opsForSet()   操作SET
    redisTemplate.opsForHash()  操作HASH
    redisTemplate.opsForZSet()  操作ZSET

6、Redis中文教程

Redis中文网

上一篇:Springboot集成Redis举例


下一篇:第七阶段:微服务开发||01-SpringBoot||18SpringBoot整合Redis【观看狂神随笔】