@Configuration
@EnableScheduling
public class RedisJob {
public static final String JOB_KEY = "redis.job.task";
private static final Logger LOGGER = LoggerFactory.getLogger(RedisJob.class);
@Autowired private StringRedisTemplate stringRedisTemplate;
public void addTask(String task, Instant instant) {
stringRedisTemplate.opsForZSet().add(JOB_KEY, task, instant.getEpochSecond());
}
@Scheduled(cron = "0 0/1 * * * ? *")
public void doDelayQueue() {
long nowSecond = Instant.now().getEpochSecond();
// 查询当前时间的所有任务
Set strings = stringRedisTemplate.opsForZSet().range(JOB_KEY, 0, nowSecond);
for (String task : strings) {
// 开始消费 task
LOGGER.info("执行任务:{}", task);
}
// 删除已经执行的任务
stringRedisTemplate.opsForZSet().remove(JOB_KEY, 0, nowSecond);
}
}