在使用springboot 註解@Async 實現異步調用時。
啓動類:
@EnableAsync//啓動異步
public class JtaAtomikosApp {
public static void main(String[] args){
SpringApplication.run(JtaAtomikosApp.class,args);
}
}
controller類:
@Autowired
private TestYiBu testYiBu;
@ResponseBody
@RequestMapping("/sendMsg")
public String sendMsg(){
System.out.println("test 異步 1");
testYiBu.sendMsg();//異步調用方法
System.out.println("test 異步 2");
return "test";
}
調用的異步類
package com.boot.other;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
@Component//注入到SpringBoot容器
public class TestYiBu {
@Async//異步加載標誌
public String sendMsg(){
System.out.println("test 異步 3");
for (int i=1; i<=3 ;i++){
System.out.println("i=" + i);
}
System.out.println("test 異步 4");
return "success";
}
}
結果輸出如下:
如圖所示,雖然實現了異步的調用,但是出現了異常:
No task executor bean found for async processing: no bean of type TaskExecutor and no bean named ‘taskExecutor’ either
解決方法:
修改啓動類如下:
@EnableAsync//啓動異步
public class JtaAtomikosApp {
public static void main(String[] args){
SpringApplication.run(JtaAtomikosApp.class,args);
}
@Bean(name = "threadPoolTaskExecutor")
public Executor threadPoolTaskExecutor() {
return new ThreadPoolTaskExecutor();
}
}
結果如圖:
其他方法:
解決方法參照:https://www.jb51.net/article/137259.htm