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);
}