1、配置文件添加
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<version>2.2.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-quartz</artifactId>
</dependency>
2、写个定时器配置的class
import com.xxx.task.RedisQuartzTask;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @ClassName QuartzConfig
* @Description 定时器配置
**/
@Configuration
public class QuartzConfig {
// 时间周期:yml文件中自定义
@Value("${xxx.redis.taskSecond}")
private int taskSecond;
@Bean
public JobDetail teatQuartzDetail(){
return JobBuilder.newJob(RedisTask.class).withIdentity("redisQuartz").storeDurably().build();
}
@Bean
public Trigger addQuartzTrigger(){
// 设置时间周期单位秒
SimpleScheduleBuilder scheduleBuilder = SimpleScheduleBuilder.simpleSchedule()
.withIntervalInSeconds(taskSecond)
.repeatForever();
return TriggerBuilder.newTrigger().forJob(teatQuartzDetail())
.withIdentity("redisQuartz")
.withSchedule(scheduleBuilder)
.build();
}
3、写个定时器
package com.xxx.task;
import com.xxx.entity.ResourceMapping;
import com.xxx.mapper.ResourceMappingMapper;
import com.xxx.service.ResourceMappingService;
import org.quartz.JobExecutionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.quartz.QuartzJobBean;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
/**
* @ClassName RedisTask
* @Description redis 定时任务
**/
public class RedisTask extends QuartzJobBean {
@Autowired
private ResourceMappingService resourceMappingService;
@Resource
private ResourceMappingMapper resourceMappingMapper;
@Resource
private RedisTemplate<String, Object> redisTemplate;
/**
* @Description: 执行定时任务
* @Param: jobExecutionContext
* @return:
* @Author: ma.kangkang
* @Date: 2019/9/30
*/
@Override
protected void executeInternal(JobExecutionContext jobExecutionContext) {
List<ResourceMapping> list = resourceMappingMapper.queryRedisList("");
Boolean ishas = operateMappingRedis(list);
if (ishas == false) {
// 重新存入redis
resourceMappingService.operateMappingRedis(list);
}
}
public Boolean operateMappingRedis(List<ResourceMapping> list) {
List<Boolean> isExistList = new ArrayList<>();
if (list.size() > 0) {
for (ResourceMapping dto : list) {
// dto.getDesc()是redis的key值
long size = redisTemplate.opsForValue().size(dto.getDesc());
// 判断redis是否存在缓存
if (size <= 0) {
// 不存在
isExistList.add(false);
}
}
}
if (isExistList.size() > 0) {
return false;
}
return true;
}
}