openFeign整合CompletableFuture實現微服務間非同步遠端呼叫並且接收結果
阿新 • • 發佈:2022-05-07
前言:關於openFeign就不廢話了,本文直接記錄在使用openFeign的基礎上整合CompletableFuture實現微服務間非同步遠端呼叫並且接收結果,非同步呼叫有很多實現方式,但大都只返回是否呼叫成功卻很少有方式可以在非同步呼叫的基礎上接收到被呼叫方返回的結果,獲取執行緒的三種方式中繼承Thread和實現Runnable都沒有返回結果,而Callable+Future可以得到返回值,因此,Future的價值可以被壓榨一番,實現了Future介面的CompletableFuture也難辭其咎,下面將對CompletableFuture進行一次簡單的壓榨。
一、服務提供方提供個介面等著被消費
Service:
@Service public class DeviceService { public String getDevice() throws InterruptedException { System.out.println("裝置服務被呼叫"); Thread.sleep(500);//模擬執行時間 return "這裡是裝置服務端!"; } }
Controller:
@Autowired private DeviceService deviceService; @RequestMapping("/d") public String deviceInfo() throws InterruptedException { String device = this.deviceService.getDevice(); return device; }
二、公共API
@FeignClient(name = "manager-device") public interface DeviceClient { @RequestMapping("/d") public String deviceInfo(); }
三、服務消費方開始遠端呼叫
Controller:
@RequestMapping("/asycgd") public String getAsycDevice() throws ExecutionException, InterruptedException { CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> { //在這呼叫 return this.deviceClient.deviceInfo(); }); //在這接收返回值 future.handle((v,e)->{ if (e != null) { //出現異常處理 e.getMessage(); }else { //v就是遠端呼叫返回來的東西 System.out.println(Thread.currentThread().getName()+":"+v); } return v; }); return future.get();//扔給前端 }
四、測試結果
啟動壓力測試工具jmeter整200個執行緒輪番壓它
明顯是非同步呼叫的,瀏覽器也得到了返回值。
關於CompletableFuture類提供的一些方法詳細用法如下.......我餓了去搶飯吃了,,,可以看下面這些,都介紹的很詳細:
https://zhuanlan.zhihu.com/p/344431341
https://zhuanlan.zhihu.com/p/378405637
Oracle官方文件在這:
https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CompletableFuture.html