您好,登錄后才能下訂單哦!
這篇文章主要為大家展示了“SpringBoot如何使用@Async”,內(nèi)容簡(jiǎn)而易懂,條理清晰,希望能夠幫助大家解決疑惑,下面讓小編帶領(lǐng)大家一起研究并學(xué)習(xí)一下“SpringBoot如何使用@Async”這篇文章吧。
注意事項(xiàng):
1. 異步方法使用static修飾
2. 異步類沒有使用@Component注解(或其他注解)導(dǎo)致spring無法掃描到異步類
3. 異步方法不能與異步方法在同一個(gè)類中
4. 類中需要使用@Autowired或@Resource等注解自動(dòng)注入,不能自己手動(dòng)new對(duì)象
5. 如果使用SpringBoot框架必須在啟動(dòng)類中增加@EnableAsync注解
6. 在Async 方法上標(biāo)注@Transactional是沒用的。 在Async 方法調(diào)用的方法上標(biāo)注@Transactional 有效。
@SpringBootApplication @EnableAsync public class Application{ public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
我們建了3個(gè)異步任務(wù),分別延遲1s,2s,3s
@Component public class AsyncTask { @Async public void task1() throws InterruptedException{ long currentTimeMillis = System.currentTimeMillis(); Thread.sleep(1000); long currentTimeMillis1 = System.currentTimeMillis(); System.out.println("task1任務(wù)耗時(shí):"+(currentTimeMillis1-currentTimeMillis)+"ms"); } @Async public void task2() throws InterruptedException{ long currentTimeMillis = System.currentTimeMillis(); Thread.sleep(2000); long currentTimeMillis1 = System.currentTimeMillis(); System.out.println("task2任務(wù)耗時(shí):"+(currentTimeMillis1-currentTimeMillis)+"ms"); } @Async public void task3() throws InterruptedException{ long currentTimeMillis = System.currentTimeMillis(); Thread.sleep(3000); long currentTimeMillis1 = System.currentTimeMillis(); System.out.println("task3任務(wù)耗時(shí):"+(currentTimeMillis1-currentTimeMillis)+"ms"); } }
@RestController @RequestMapping("/test") public class TestController { @Autowired private AsyncTask asyncTask; @RequestMapping("/async") public String doTask() throws InterruptedException{ long currentTimeMillis = System.currentTimeMillis(); asyncTask.task1(); asyncTask.task2(); asyncTask.task3(); long currentTimeMillis1 = System.currentTimeMillis(); return "task任務(wù)總耗時(shí):"+(currentTimeMillis1-currentTimeMillis)+"ms"; } }
啟動(dòng)SpringBoot服務(wù),訪問/test/async接口,能看到任務(wù)耗時(shí)只有1s
查看控制臺(tái),發(fā)現(xiàn)異步task也成功執(zhí)行了!
以上是“SpringBoot如何使用@Async”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對(duì)大家有所幫助,如果還想學(xué)習(xí)更多知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。