版權聲明:本文爲博主原創文章,無需授權即可轉載,甚至無需保留以上版權聲明,轉載時請務必註明作者。
https://blog.csdn.net/weixin_43453386/article/details/106209402
同步調用 :整個處理過程按順序執行,每一步必須等到上一步執行完後才能執行
異步調用 :只是發送了調用的指令,調用者無需等待被調用的方法完全執行完畢,繼續執行下面的流程。
一、開啓異步:@EnableAsync
@EnableAsync
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
二、實現異步:@Async
1、Service代碼示例
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;
import java.util.concurrent.Future;
/**
* <p>
* 異步 服務類
* </p>
*
* @author xiaoxian
* @since 2020-05-19
*/
@Service
public class AsyncService {
/**
* 無返回值
*/
@Async
public void asyncWithNoReturn() {
System.out.println("開始執行asyncWithNoReturn...");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("結束執行asyncWithNoReturn...");
}
/**
* 有返回值
* @return
*/
@Async
public Future<String> asyncWithReturn() {
System.out.println("開始執行asyncWithReturn...");
Future<String> future = new AsyncResult<>("success");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
future = new AsyncResult<String>("error");
}
System.out.println("開始執行asyncWithReturn...");
return future;
}
}
2、Controller代碼示例
import com.eju.fangshop.core.service.AsyncService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
/**
* <p>
* 異步 前端控制器
* </p>
*
* @author lz
* @since 2020-05-14
*/
@RestController
public class AsyncController{
@Autowired
AsyncService asyncService;
/**
* 調用無返回值方法
* @return
*/
@GetMapping("/asyncWithNoReturn")
public String asyncWithNoReturn(){
asyncService.asyncWithNoReturn();
return "success";
}
/**
* 調用有返回值方法
* get()方法的作用是獲取執行結果,此方法會產生阻塞,等到任務執行完畢後才能獲得執行結果
* @return
*/
@GetMapping("/asyncWithReturn")
public String asyncWithReturn(){
String result = null;
Future<String> future = asyncService.asyncWithReturn();
try {
result = future.get();
} catch (InterruptedException e) {
e.printStackTrace();
result = "error";
} catch (ExecutionException e) {
e.printStackTrace();
result = "error";
}
return result;
}
}
三、測試異步
啓動項目,打開postman,進行測試
1、測試無返回值
- url:http://127.0.0.1:8902/asyncWithNoReturn
- status:200
- time:17ms
如下圖所示,發送請求後,立即返回結果。
2、測試有返回值
- url:http://127.0.0.1:8902/asyncWithReturn
- status:200
- time:3.02s
如下圖所示,由於我們調用了get()方法,發送請求後,會在3000毫秒後,纔會返回結果。