同樣是拿別人的,整體沒報錯,不過還未經具體測試
配置類:
package com.tansuo365.test1.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.task.TaskExecutor; import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import java.util.concurrent.ThreadPoolExecutor; @Configuration @EnableAsync public class AsyncConfig { @Bean public TaskExecutor taskExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); // 設置核心線程數 executor.setCorePoolSize(5); // 設置最大線程數 executor.setMaxPoolSize(10); // 設置隊列容量 executor.setQueueCapacity(20); // 設置線程活躍時間(秒) executor.setKeepAliveSeconds(60); // 設置默認線程名稱 executor.setThreadNamePrefix("danhao-"); // 設置拒絕策略 executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); // 等待所有任務結束后再關閉線程池 executor.setWaitForTasksToCompleteOnShutdown(true); return executor; } }
注意配置類的新注解 @EnableAsync
控制層:
@Async @RequestMapping("/getChukuNumber") public ListenableFuture<String> genBillCode(String type) throws Exception { StringBuffer billCodeStr = new StringBuffer(); billCodeStr.append(chukudanPrefix); billCodeStr.append(DateUtil.getCurrentDateStr()); String todayMaxChukuDanNumber = chukuZongService.getTodayMaxChukuDanNumber(); if (todayMaxChukuDanNumber != null) { billCodeStr.append(StringUtil.formatCode(todayMaxChukuDanNumber)); } else { billCodeStr.append("0001"); } return new AsyncResult<>(billCodeStr.toString()); // return billCodeStr.toString(); }
注意控制層的返回類型 返回值 以及新注解@Async
同樣的啟動類上:
//@EnableCaching @SpringBootApplication @MapperScan(value = {"com.xxxxxxxxx.test1.mapper"}) @EnableAsync//開啟異步任務 public class Test1Application { public static void main(String[] args) { SpringApplication.run(Test1Application.class, args); } }
注意啟動類上的 @EnableAsync 注解
