在Spring Boot项目中,自定义组件类,实现ApplicationRunner
接口,则重写的方法会在项目启动时自动执行,可以在此重写的方法中向Redis存入缓存的数据,即可实现缓存预热(启动项目时即加载缓存数据到Redis中)。
示例代码:ICategoryService
:
/**
* 重建缓存
*/
void rebuildCache();
示例代码:CategoryServiceImpl
:
@Override
public void rebuildCache() {
List<CategoryListItemVO> list
= categoryRepository.list(1, Integer.MAX_VALUE).getList();
categoryCacheRepository.deleteList();
categoryCacheRepository.saveList(list);
}
示例代码:CategoryCachePreload
:
@Slf4j
@Component
public class CategoryCachePreload implements ApplicationRunner {
@Autowired
private ICategoryService categoryService;
@Override
public void run(ApplicationArguments args) throws Exception {
categoryService.rebuildCache();
}
}