- redis的安裝
在筆者之前的文章中有介紹redis的安裝煌张,不會的可以去看 筆者之前寫的文章redis安裝 - 完成安裝后如果不熟悉redis的操作润讥,redis官方文檔也有基本操作指南庇绽,redis基本操作,如果覺得沒問題了就可以開始對redis的整合
- maven安裝依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
redis自動會吧cache的依賴帶過來,所有不用配置,如圖
- 啟動類增加@EnableCaching 注解
@SpringBootApplication
@MapperScan("com.tanoak.mapper")
@EnableCaching
public class BootRedisApplication {
public static void main(String[] args) {
SpringApplication.run(BootRedisApplication.class, args);
}
}
- service層增加@Cacheable 注解
@Override
@Cacheable(cacheNames= "tea")
public Teacher getTeaById(Integer id) {
logger.info("進行查詢實體 ID為"+id);
return teacherMapper.getTeaById(id) ;
}
- controller 查詢
@GetMapping("/tea/{id}")
public Teacher getTea(@PathVariable("id")Integer id){
return teacherService.getTeaById(id) ;
}
RedisCacheManager 配置
在SpringBoot2.x中茎截,移除了1.x中的配置苇侵,因此要配置Json序列化與1.x的差別很大赶盔,看代碼
@Configuration
@EnableCaching
public class MyRedisConfig extends CachingConfigurerSupport {
/*
*自定義鍵生成策略
*/
@Bean
public KeyGenerator KeyGenerator() {
return (target, method, params) -> {
StringBuilder sb = new StringBuilder();
sb.append(target.getClass().getName());
sb.append(method.getName());
for (Object obj : params) {
sb.append(obj.toString());
}
return sb.toString();
};
}
@Bean
public RedisCacheConfiguration redisCacheConfiguration() {
Jackson2JsonRedisSerializer<Object> 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 redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig();
redisCacheConfiguration = redisCacheConfiguration.serializeValuesWith(
RedisSerializationContext
.SerializationPair
.fromSerializer(jackson2JsonRedisSerializer)
//設置默認超過期時間是30秒
).entryTtl(Duration.ofMinutes(30));
return redisCacheConfiguration;
}
}
沒有打印sql,說明緩存成功榆浓,與redis集成就完成了