1、首先使用@Async 需要在Spring啟動類上添加注解@EnableAsyn或者在你們線程池配置類添加@EnableAsyn
一下兩種選擇一種即可
@SpringBootApplication @EnableAsync public class SpringBootApplicationStart { public static void main(String[] args) { SpringApplication.run(SpringBootApplicationStart.class); } }
@EnableAsync @Configuration public class ThreadPoolConfig { @Bean("simpleThreadPool") public ThreadPoolTaskExecutor simpleThreadPool(){ ThreadPoolTaskExecutor simpleThreadPool = new ThreadPoolTaskExecutor(); simpleThreadPool.setCorePoolSize(5); simpleThreadPool.setMaxPoolSize(10); simpleThreadPool.setQueueCapacity(25); simpleThreadPool.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); simpleThreadPool.initialize(); return simpleThreadPool; } }
注意如果自己配置了線程池那么在使用的時候需要保持一致
例如:@Async("simpleThreadPool")
2、在使用@Async的時候切記不要在一個類里面調用@Async聲明的方法,會產生代理繞過問題。
@Async public void asyncProcess() throws InterruptedException { Thread.sleep(2000); }
3、注意寫法
@Autowired private AsyncTaskService asyncTaskService; public String asyncMethod(String name,int age) { OnelogStats.trace("msg_async", "進入service"); try { // 初學者可能會有這種錯誤,AsyncTaskService沒有注入到Spring導致Async不起作用,注釋不規范 //new AsyncTaskService().asyncProcess(); asyncTaskService.asyncProcess(); } catch (InterruptedException e) { return "async error"; } return "I am " + name + ", I am " + age + " years old."; }