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中文網


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM