一、需求:
定时从redis中取缓存数据并存入MySQL
二、实现步骤
1.controller层
package com.itsys.monitor.controller;
import com.itsys.monitor.common.RedisUtil;
import com.itsys.monitor.conf.MyRunnable;
import com.itsys.monitor.model.ReturnDTO;
import com.itsys.monitor.model.ReturnState;
import com.itsys.monitor.service.ElectricRecordService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.concurrent.ScheduledFuture;
@Slf4j
@RestController
@RequestMapping("/task")
public class DynamicTaskController {
@Autowired
private ThreadPoolTaskScheduler threadPoolTaskScheduler;
@Autowired
private RedisUtil redisUtil;
@Autowired
private ElectricRecordService service;
private ScheduledFuture<?> future;
@Bean
public ThreadPoolTaskScheduler threadPoolTaskScheduler() {
return new ThreadPoolTaskScheduler();
}
@PostMapping("/start")
public ReturnDTO startCron1() {
if (future != null) {
future.cancel(true);
}
future = threadPoolTaskScheduler.schedule(new MyRunnable(service,redisUtil), triggerContext -> {
String cTime = (String) redisUtil.get("cTime");
String cron;
if (Integer.parseInt(cTime) == 60){
cron = "0 0 */1 * * ?";
}else {
cron = "0 0/"+cTime+" * * * ?";
}
return new CronTrigger(cron).nextExecutionTime(triggerContext);
});
return ReturnState.setSuccessStatus();
}
@PostMapping("/stop")
public ReturnDTO stopCron1() {
if (future != null) {
future.cancel(true);
}
System.out.println("DynamicTask.stopCron1()");
return ReturnState.setSuccessStatus();
}
}
2.任务实现类
package com.itsys.monitor.conf;
import com.itsys.monitor.common.RedisUtil;
import com.itsys.monitor.model.ElectricRecord;
import com.itsys.monitor.service.ElectricRecordService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import java.util.Map;
@Slf4j
public class MyRunnable implements Runnable {
private ElectricRecordService service;
private RedisUtil redisUtil;
public MyRunnable(ElectricRecordService service, RedisUtil redisUtil) {
this.service = service;
this.redisUtil = redisUtil;
}
@SneakyThrows
@Override
public void run() {
Map<Object, Object> map = redisUtil.hmget("electric");
log.info("持久化电流数据【{}】", map);
map.forEach((key, value) -> service.add((ElectricRecord) value));
}
}