springboot2.x版本redis缓存学习
程序员文章站
2022-07-07 11:37:16
...
springboot2.x版本redis缓存学习
在springboot1.x版本redis缓存学习的基础上,学习扩展2.x版本的更改
添加依赖
和1.x版本一样
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
自定义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
示例
推荐阅读
-
Redis缓存技术学习系列之事务处理 springmvc+mybatisdubbo+zookeeperrestful redis分布式缓存spring mvc
-
Redis缓存技术学习系列之事务处理 springmvc+mybatisdubbo+zookeeperrestful redis分布式缓存spring mvc
-
SpringBoot2.X学习(三):缓存
-
springboot2.x redis做缓存
-
springboot2.x中,shiro使用redis缓存
-
SpringBoot2.x整合Redis进行数据缓存
-
springboot2.x整合redis实现缓存
-
springboot2.x版本redis缓存学习
-
springboot2.X Redis接口缓存
-
SpringBoot学习(七)使用Redis进行缓存,注解方式