springboot2.x版本redis缓存学习

springboot2.x版本redis缓存学习

在springboot1.x版本redis缓存学习的基础上,学习扩展2.x版本的更改

添加依赖

和1.x版本一样


	org.springframework.boot
	spring-boot-starter-cache


	org.springframework.boot
	spring-boot-starter-data-redis

自定义redis项目前缀和配置redis缓存有效期

注意这里和1.x版本的区别,配置前缀的方式和配置value序列化的方式

@Configuration
@EnableCaching
@Slf4j
public class RedisConfig extends CachingConfigurerSupport {

    @Value("${spring.application.name:unknown}")
    private String appName;
    @Value("${spring.redis.timeToLive:600s}")
    private Duration timeToLive;

    @Bean
    public CacheManager cacheManager(RedisConnectionFactory factory) {
        RedisSerializer<String> redisSerializer = new StringRedisSerializer();
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);

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

        // 配置序列化(解决乱码的问题)
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
                .entryTtl(timeToLive)
                .prefixKeysWith(appName + ":")
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer))
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer))
                // 是否允许控制存储
                .disableCachingNullValues();

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

配置yml

spring:
  application:
    name: spring-boot2-redis-cache
  redis:
    host: 192.168.0.0
    port: 6379
    database: 7
    timeout: 1s

示例

点击下载源码,如果对你有帮助请赏赐一个star

你可能感兴趣的:(SpringBoot)