@RequestMapping("/job/")
@RestController
public class JobResource {
@Autowired
private JobService jobService;
/**
* 添加延时消息
*
* @param jobDTO
* @return
* @throws Exception
*/
@RequestMapping(value = "add", method = RequestMethod.POST)
public Boolean addJob(@RequestBody JobDTO jobDTO) throws Exception {
return jobService.addJob(jobDTO);
}
/**
* 延时消息回调测试
*
* @param messageId
* @param map
* @return
* @throws Exception
*/
@RequestMapping(value = "test/{messageId}", method = RequestMethod.POST)
public Map addJob(@PathVariable(name = "messageId") String messageId, @RequestBody Map<String, Object> map) throws Exception {
System.out.println("回调执行的messageId:" + messageId);
return map;
}
@Service
public class JobServiceImpl implements JobService {
@Override
public Boolean addJob(JobDTO jobDTO) {
ScheduledExecutorService executorService = Executors.newScheduledThreadPool(4);
System.out.println("添加任务时间:" + System.currentTimeMillis());
executorService.schedule(new Task(jobDTO), jobDTO.getDelayedTimeMillis(), TimeUnit.MILLISECONDS);
return Boolean.TRUE;
}
private static class Task implements Runnable {
private final JobDTO jobDTO;
Task(JobDTO jobDTO) {
this.jobDTO = jobDTO;
}
@Override
public void run() {
System.out.printf("执行任务时间:%s,messageId:%s,callbackUrl:%s,param:%s%n", System.currentTimeMillis(), jobDTO.getId(), jobDTO.getCallback(), jobDTO.getBody());
if (StringUtils.isNotBlank(jobDTO.getCallback())) {
String url = jobDTO.getCallback().endsWith("/") ? jobDTO.getCallback() + jobDTO.getId() : jobDTO.getCallback() + "/" + jobDTO.getId();
String body = Unirest.post(url).header("Content-Type", "application/json").body(jobDTO.getBody()).asString().getBody();
System.out.println("延迟请求响应:" + body);
}
}
}
}
向ScheduledExecutorService添加任务,指定延迟时间,会自动调用Task线程的方法。