Springboot任務之異步任務的使用詳解
一、SpringBoot--異步任務
1.1 什么是同步和異步
- 同步是阻塞模式,異步是非阻塞模式。
- 同步就是指一個進程在執(zhí)行某個請求的時候,若該請求需要一段時間才能返回信息,那么這個進程將會—直等待下去,知道收到返回信息才繼續(xù)執(zhí)行下去
- 異步是指進程不需要一直等下去,而是繼續(xù)執(zhí)行下面的操作,不管其他進程的狀態(tài)。當有消息返回式系統(tǒng)會通知進程進行處理,這樣可以提高執(zhí)行的效率。
1.2 Java模擬一個異步請求(線程休眠)

AsyncService.java
package com.tian.asyncdemo.service;
import org.springframework.stereotype.Service;
@Service
public class AsyncService {
public void hello() {
try {
System.out.println("數(shù)據(jù)正在處理");
Thread.sleep(3000);
System.out.println("數(shù)據(jù)處理完成");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

AsyncController.java
package com.tian.asyncdemo.controller;
import com.tian.asyncdemo.service.AsyncService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* ClassName: AsyncController
* Description:
*
* @author Administrator
* @date 2021/6/6 19:48
*/
@RestController
public class AsyncController {
@Autowired
AsyncService asyncService;
@RequestMapping("/hello")
public String hello() {
asyncService.hello();
return "OK";
}
}
運行結果:

1.3 使用異步
在Service的方法中使用@Async說這是一個異步方法,并在主入口上使用@EnableAsync開啟異步支持

AsyncService.java
@Service
public class AsyncService {
@Async
public void hello() {
try {
System.out.println("數(shù)據(jù)正在處理");
Thread.sleep(3000);
System.out.println("數(shù)據(jù)處理完成");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
主入口上使用@EnableAsync開啟異步支持

再次測試:

到此這篇關于Springboot任務之異步任務的使用詳解的文章就介紹到這了,更多相關SpringBoot異步任務內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
springboot 運行 jar 包讀取外部配置文件的問題
這篇文章主要介紹了springboot 運行 jar 包讀取外部配置文件,本文主要描述linux系統(tǒng)執(zhí)行jar包讀取jar包同級目錄的外部配置文件,主要分為兩種方法,每種方法通過實例代碼介紹的非常詳細,需要的朋友可以參考下2021-07-07
Spring @Retryable注解輕松搞定循環(huán)重試功能
spring系列的spring-retry是另一個實用程序模塊,可以幫助我們以標準方式處理任何特定操作的重試。在spring-retry中,所有配置都是基于簡單注釋的。本文主要介紹了Spring@Retryable注解如何輕松搞定循環(huán)重試功能,有需要的朋友可以參考一下2023-04-04
Spring Boot集成ElasticSearch實現(xiàn)搜索引擎的示例
這篇文章主要介紹了Spring Boot集成ElasticSearch實現(xiàn)搜索引擎的示例,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-11-11
在spring?boot3中使用native?image的最新方法
這篇文章主要介紹了在spring?boot3中使用native?image?,今天我們用具體的例子來給大家演示一下如何正確的將spring boot3的應用編譯成為native image,需要的朋友可以參考下2023-01-01

