SpringBoot配置Redis

刘哲贤 7月前 ⋅ 1663 阅读

在springboot中整合redis:

1.先导入redis的maven的依赖。代码如下:

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

2.在application.yml中加入配置:

spring:
    redis:
    database: 0
    host: 127.0.0.1
    port: 6379
    password:    #有密码的填密码,默认没有
    

3.添加RedisConfig 配置类:

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
@EnableCaching
public class RedisConfig {

    @Autowired
    private ObjectMapper objectMapper;

    /**
     * 自定义springSessionDefaultRedisSerializer对象,将会替代默认的SESSION序列化对象。
     * 默认是JdkSerializationRedisSerializer,缺点是需要类实现Serializable接口。
     * 并且在反序列化时如果异常会抛出SerializationException异常,
     * 而SessionRepositoryFilter又没有处理异常,故如果序列化异常时就会导致请求异常
     */
    @Bean(name = "springSessionDefaultRedisSerializer")
    public GenericJackson2JsonRedisSerializer getGenericJackson2JsonRedisSerializer() {
        return new GenericJackson2JsonRedisSerializer();
    }

    /**
     * JacksonJsonRedisSerializer和GenericJackson2JsonRedisSerializer的区别:
     * GenericJackson2JsonRedisSerializer在json中加入@class属性,类的全路径包名,方便反系列化。
     * JacksonJsonRedisSerializer如果存放了List则在反系列化的时候,
     * 如果没指定TypeReference则会报错java.util.LinkedHashMap cannot be cast。
     */
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(connectionFactory);

        // 使用Jackson2JsonRedisSerialize 替换默认序列化
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer =
                new Jackson2JsonRedisSerializer(Object.class);

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

        redisTemplate.setHashKeySerializer(jackson2JsonRedisSerializer);
        redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);

        redisTemplate.setDefaultSerializer(jackson2JsonRedisSerializer);
        redisTemplate.setEnableDefaultSerializer(true);
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }

}

完成上述操作,恭喜完成Redis在项目中的配置!!!


全部评论: 0

    我有话说: