1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
| @Service public class ReportService { @Autowired private ThreadPoolTaskExecutor asyncExecutor; @Autowired private RedisTemplate<String, Object> redisTemplate;
public void submitAsyncReportTask(String taskId, LocalDate startDate, LocalDate endDate) { ReportTask task = new ReportTask(); task.setTaskId(taskId); task.setStartDate(startDate); task.setEndDate(endDate); task.setStatus("PROCESSING"); task.setCreateTime(LocalDateTime.now()); redisTemplate.opsForValue().set("report:task:" + taskId, task, Duration.ofHours(24)); asyncExecutor.submit(() -> { try { processAsyncReport(taskId, startDate, endDate); } catch (Exception e) { handleAsyncReportError(taskId, e); } }); }
private void processAsyncReport(String taskId, LocalDate startDate, LocalDate endDate) { try { log.info("开始处理异步报表任务: {}, 时间范围: {} - {}", taskId, startDate, endDate); List<OrderDailyReport> reports = getDailyReportBySegment(startDate, endDate); OrderReport finalReport = aggregateSegmentReports(reports); updateTaskStatus(taskId, "COMPLETED", finalReport); log.info("异步报表任务完成: {}", taskId); } catch (Exception e) { log.error("异步报表任务失败: {}", taskId, e); throw e; } }
private void handleAsyncReportError(String taskId, Exception e) { ReportTask task = new ReportTask(); task.setTaskId(taskId); task.setStatus("FAILED"); task.setErrorMessage(e.getMessage()); task.setUpdateTime(LocalDateTime.now()); redisTemplate.opsForValue().set("report:task:" + taskId, task, Duration.ofHours(24)); alertService.sendAlert("异步报表任务失败", "任务ID: " + taskId + ", 错误: " + e.getMessage()); }
private void updateTaskStatus(String taskId, String status, OrderReport report) { ReportTask task = (ReportTask) redisTemplate.opsForValue().get("report:task:" + taskId); if (task != null) { task.setStatus(status); task.setUpdateTime(LocalDateTime.now()); task.setResult(report); redisTemplate.opsForValue().set("report:task:" + taskId, task, Duration.ofHours(24)); } }
public ReportTask getTaskStatus(String taskId) { return (ReportTask) redisTemplate.opsForValue().get("report:task:" + taskId); } }
|