问题:第一个用户访问还是很慢(加入第一个老板),也能一定程度上保护数据库
缓存预热的优点:
缺点:
定时
模拟触发(手动触发)
用定时任务,每天刷新所有用户的推荐列表
注意点:
第一种方式:
cron 表达式
package com.bo.partner.job;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bo.partner.mapper.UserMapper;
import com.bo.partner.model.domain.User;
import com.bo.partner.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;
/**
* @author: bo
* @date: 2022/9/13
* @description:
*/
@Component
@Slf4j
public class PreCacheJob {
//每天执行
//重点用户
private List mainUserList = Arrays.asList(1L);
@Resource
private RedisTemplate redisTemplate;
@Resource
private UserService userService;
@Resource
private UserMapper userMapper;
@Scheduled(cron = "0 42,46 * * * *")
public void doCatchRecommendUser() {
for (Long userId : mainUserList) {
QueryWrapper queryWrapper = new QueryWrapper<>();
Page page = userService.page(new Page<>(1, 20), queryWrapper);
String redisKey = String.format("partner:user:recommed:userId", userId);
ValueOperations valueOperations = redisTemplate.opsForValue();
try {
valueOperations.set(redisKey, page, 10000, TimeUnit.MILLISECONDS);
} catch (Exception e) {
log.error("redis set key error", e);
}
}
}
}