Springboot集成SpringCache + Redis,以利用SpringCache的註解和Redis的存儲、過期等。
(一)自定義緩存配置文件
@Configuration
public class CacheConfiguration {
/**
* 搜索小說緩存
*/
public static final String BOOKS_SEARCH_CACHE = "books_search";
/**
* 章節內容緩存
*/
public static final String CHAPTERS_BOOK_CACHE = "chapters_book";
/**
* 章節內容緩存
*/
public static final String CHAPTER_CONTENT_CACHE = "chapter_content";
@Primary
@Bean
public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory){
RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig();
redisCacheConfiguration = redisCacheConfiguration
//設置緩存的默認超時時間:30分鐘
.entryTtl(Duration.ofMinutes(30L))
//如果是空值,不緩存
.disableCachingNullValues()
//設置key序列化器
.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(keySerializer()))
//設置value序列化器
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(valueSerializer()));
return RedisCacheManager
.builder(RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory))
.cacheDefaults(redisCacheConfiguration)
.build();
}
/**
* key序列化器
*/
private RedisSerializer<String> keySerializer() {
return new StringRedisSerializer();
}
/**
* value序列化器
*/
private RedisSerializer<Object> valueSerializer() {
return new GenericJackson2JsonRedisSerializer();
}
}
(二)開啓緩存
@EnableCaching:開啓緩存
@SpringBootApplication
@ServletComponentScan
@MapperScan("com.yuedu.dao")
@EnableScheduling
@EnableCaching
public class YueduApplication {
public static void main(String[] args) {
SpringApplication.run(YueduApplication.class, args);
}
}
(三)應用
@Cacheable(cacheNames = CacheConfiguration.CHAPTERS_BOOK_CACHE, key = "#root.methodName+'['+#bookId+']'")
public List<Chapter> searchChaptersByBookId(Integer bookId, int start, int size) {
if (bookId == null || bookId < 1){
throw new BaseException(ResultEnum.PARAM_ERROR);
}
Chapter chapter = new Chapter();
chapter.setBookId(bookId);
//設置分頁
PageHelper.startPage(start, size);
return selectChapters(chapter);
}