关于缓存预热
应用场景
比如:一个系统中第一个用户访问很慢 此时还没有缓存 这时候就可以使用缓存预热 再比如双十一 用户数量那么多 如果每个人第一次访问时候都得在服务器上查询一次数据库 再将查询结果存入缓存中 这样太慢了
缓存预热的优点和缺点
- 优点
1.解决上面的问题 也在一定的程度上保护数据库可以让用户始终访问很快
- 缺点
1.增加开发成本
2需要占用额外的空间
3.预热的时机如果错了 有可能使你的缓存数据太老或者不适合
怎么使用缓存预热?
1.定时
2.手动触发
使用@Scheduler
1.在spring的启动类上添加注解@EnableScheduling
@EnableScheduling
public class UserCenterApplication {
public static void main(String[] args) {
SpringApplication.run(UserCenterApplication.class, args);
log.info("启动成功");
}
2.在@Scheduler上添加cron表达式
private List<Long> mainUserList= (List<Long>) Arrays.asList(1L);
@Scheduled(cron = "0 59 17 * * *")
public void doCacheRecommendUser(){
for (Long userId : mainUserList) {
String RedisKey = String.format("lulu:user:recommend:userId:%s",userId);
ValueOperations<String, Object> opsForValue = redisTemplate.opsForValue();
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
Page<User> userPage = userService.page(new Page<>(1, 20), queryWrapper);
//写缓存
try {
opsForValue.set(RedisKey,userPage,30000, TimeUnit.MILLISECONDS);
} catch (Exception e) {
log.info("redis set key err",e);
}
}
}
上面表示的是在每年每星期每日的17:59 0秒 都会执行一次任务