SpringBoot2.x整合redis和使用redis缓存

springboot1.x和2.x对于整合redis略有不同,需注意。

1、依赖、配置文件

先引入redis的starter:


<dependency>
    <groupId>org.springframework.bootgroupId>
    <artifactId>spring-boot-starter-data-redisartifactId>
dependency>

<dependency>
    <groupId>org.springframework.bootgroupId>
    <artifactId>spring-boot-starter-cacheartifactId>
dependency>
View Code

然后是在properties或者yml中配置基本信息

# Redis连接池属性
spring.redis.jedis.pool.mix-idle=5
spring.redis.jedis.pool.max-active=10
spring.redis.jedis.pool.max-idle=10
spring.redis.jedis.pool.max-wait=2000
## Redis服务器属性
spring.redis.port=6379
spring.redis.host=127.0.0.1
spring.redis.password=root
spring.redis.timeout=1000
spring.redis.database=1
## redis缓存管理器
spring.cache.type=REDIS
spring.cache.cache-names=redisCache
spring.cache.redis.use-key-prefix=false
spring.cache.redis.time-to-live=600000
View Code

2、配置序列化器

如果我们没有配置序列化器,可能显示的数据是这样的:
SpringBoot2.x整合redis和使用redis缓存_第1张图片

 

 我们需要存储一个对象,并且能够很好阅读,那我们就需要自定义序列化器,将数据以json的方法显示:

SpringBoot2.x整合redis和使用redis缓存_第2张图片

 

 代码如下:

@Configuration
public class RedisConfig extends CachingConfigurerSupport {

    //配置Redistemplate
    @Bean
    public RedisTemplate redisTemplate(
            RedisConnectionFactory redisConnectionFactory)
            throws UnknownHostException {
        RedisTemplate template = new RedisTemplate<>();
        template.setConnectionFactory(redisConnectionFactory);

        // 使用Jackson2JsonRedisSerialize 替换默认序列化
        Jackson2JsonRedisSerializer serializer = new Jackson2JsonRedisSerializer<>(Object.class);
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        objectMapper.activateDefaultTyping(objectMapper.getPolymorphicTypeValidator(),ObjectMapper.DefaultTyping.NON_FINAL);
        serializer.setObjectMapper(objectMapper);

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

        return template;
    }

    //使用CacheManager缓存
    @Bean
    public CacheManager cacheManager(RedisConnectionFactory factory) {
        RedisSerializer redisSerializer = new StringRedisSerializer();
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);

        //解决查询缓存转换异常的问题
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.activateDefaultTyping(om.getPolymorphicTypeValidator(),ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);

        // 配置序列化(解决乱码的问题),过期时间30秒
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
                .entryTtl(Duration.ofSeconds(1800000))
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer))
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer))
                .disableCachingNullValues();

        RedisCacheManager cacheManager = RedisCacheManager.builder(factory)
                .cacheDefaults(config)
                .build();
        return cacheManager;
    }
} 
   
  View Code 
  
 

3、其他

对于Redistemplate来说,每一次使用都要加上opsForValue等这些,我们可以自己编写一个工具类,用简单一点的名字来代替这些繁琐的操作,网上的例子很多,这里不赘述了。

 

你可能感兴趣的:(SpringBoot2.x整合redis和使用redis缓存)