非同步操作優化介面效能,可提升數倍
阿新 • • 發佈:2021-01-26
技術標籤:javase介面效能優化介面效能Completable非同步優化介面效能
背景:
在我們日常的開發中,很多時候我們的介面會有比較複雜的邏輯,比如說在一個介面中我們可能要去查詢N次資料庫來獲得我們想要的資料,然後做一些邏輯運算,引數拼裝等,還可能呼叫第三方的api,這會讓我們的介面不堪重負。
實戰
其實在很多操作其實是沒必要序列的,會浪費掉我們計算機的效能,還增加了介面的開銷時間,這時我們可以通過並行也就是非同步來優化我們介面的。
比如有這樣的場景,我們需要去呼叫三個第三方的api獲取結果後並且相加,每個api大概需要花2s
程式碼:
public int getA(){ try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } return 1; } public int getB(){ try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } return 2; } public int getC(){ try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } return 3; } @org.junit.Test public void api() throws ExecutionException, InterruptedException { long startTime = System.currentTimeMillis(); int a = getA(); int b = getB(); int c = getC(); System.out.println(a+b+c); long endTime = System.currentTimeMillis(); System.out.println("total expense = {},"+(endTime-startTime)); }
執行結果:
總共需要6S多的時間,這樣的序列計算,其實沒法發揮出多核計算機的優勢,我們使用非同步來優化我們的介面:
@org.junit.Test public void apiOp() throws ExecutionException, InterruptedException { long startTime = System.currentTimeMillis(); CompletableFuture a = CompletableFuture.supplyAsync(() -> { return getA(); }); CompletableFuture b = CompletableFuture.supplyAsync(() -> { return getB(); }); CompletableFuture c = CompletableFuture.supplyAsync(() -> { return getC(); }); System.out.println((int)a.get() + (int)b.get()+ (int)c.get()); long endTime = System.currentTimeMillis(); System.out.println("total expense = {},"+(endTime-startTime)); }
可以看到我們的介面效能提升近3倍。
CompletableFuture是jdk8中的類, 提供了四個靜態方法來建立一個非同步操作
public static CompletableFuture<Void> runAsync(Runnable runnable) public static CompletableFuture<Void> runAsync(Runnable runnable, Executor executor) public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier) public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier, Executor executor)
runAsyn方法不支援返回值,supplyAsync可以支援返回值,有興趣的可以自己學一下,網上資料一大把的。