建立一個線程池 @EnableAsync public class AsyOrderConfig implements AsyncConfigurer { @Override @Bean public Executor getAsyncExecutor() { // 獲取線程池 – 數據庫的鏈接池 ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor(); // 設置線程數 threadPoolTaskExecutor.setCorePoolSize(10); // 設置最大鏈接數 threadPoolTaskExecutor.setMaxPoolSize(100); // 設置等待隊列,若是10個不夠,能夠有100個線程等待 緩衝池 threadPoolTaskExecutor.setQueueCapacity(100); // 初始化操做 threadPoolTaskExecutor.initialize(); return threadPoolTaskExecutor; } @Override public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() { return null; } /** * 在代碼中的方法上能夠標記@Async * // 處理未完成訂單 * @Async * public void execExpiredOrder(OrderInfo orderInfo){ * // 訂單信息 * updateOrderStatus(orderInfo.getId(),ProcessStatus.CLOSED); * // 付款信息 * paymentService.closePayment(orderInfo.getId()); * } */ }
/** * 定時處理過時訂單 * */ @EnableScheduling @Component public class OrderTask { @Scheduled(cron = "0/20 * * * * ?") public void checkOrder() { System.out.println("開始處理過時訂單"); long starttime = System.currentTimeMillis(); List<OrderInfo> expiredOrderList = orderService.getExpiredOrderList(); for (OrderInfo orderInfo : expiredOrderList) { // 處理未完成訂單 orderService.execExpiredOrder(orderInfo); } long costtime = System.currentTimeMillis() - starttime; System.out.println("一共處理"+ " " +"個訂單 共消耗"+costtime+"毫秒"); } }