閱文集團旗下哪個網(wǎng)站做的最好seo培訓一對一
背景
今天在開發(fā)質(zhì)量平臺時需要獲取某些數(shù)據(jù),要請求公司某個工程的OpenAPI接口A。此接口為返回通用數(shù)據(jù)的接口,且接口本身的RT都在2~3秒之間。使用該接口,需要進行兩次循環(huán)獲取,然后對返回數(shù)據(jù)進行處理組裝,才能得到我這邊工程需要的數(shù)據(jù)。
在最開始的時候,我天真的寫了兩層循環(huán),外層循環(huán)為一星期的每一天,內(nèi)層循環(huán)為選取的幾個版本號。結(jié)果發(fā)現(xiàn)整個請求過程(請求接口B和C獲取版本相關(guān)數(shù)據(jù)->兩層循環(huán)請求接口A->數(shù)據(jù)過濾篩選->數(shù)據(jù)組裝排序)下來,響應時間來到了恐怖的2分鐘(🤔要被領(lǐng)導罵死了)
同時數(shù)據(jù)又都要實時獲取,無法使用定時任務和緩存的方式
解決思路
將for循環(huán)改為多線程的方式進行執(zhí)行,一種常用的方法是使用Executor框架
package com.xxx.xxx;...
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;public class Main {public static void main(String[] args) {// 模擬數(shù)據(jù)庫中的100條數(shù)據(jù);List list = new ArrayList();for (int i = 0; i < 100; i++) {list.add(i);}//Executors創(chuàng)建線程池new固定的10個線程ExecutorService taskExecutor = Executors.newCachedThreadPool();final CountDownLatch latch = new CountDownLatch(list.size());//用于判斷所有的線程是否結(jié)束System.out.println("個數(shù)==" + list.size());for (int m = 0; m < list.size(); m++) {final int n = m;//內(nèi)部類里m不能直接用,所以賦值給nRunnable run = new Runnable() {public void run() {try {System.out.println("我在執(zhí)行=" + n);} finally {latch.countDown(); //每次調(diào)用CountDown(),計數(shù)減1}}};taskExecutor.execute(run);//開啟線程執(zhí)行池中的任務。還有一個方法submit也可以做到,它的功能是提交指定的任務去執(zhí)行并且返回Future對象,即執(zhí)行的結(jié)果}try {//等待所有線程執(zhí)行完畢latch.await();//主程序執(zhí)行到await()函數(shù)會阻塞等待線程的執(zhí)行,直到計數(shù)為0} catch (InterruptedException e) {e.printStackTrace();}taskExecutor.shutdown();//關(guān)閉線程池//所有線程執(zhí)行完畢,執(zhí)行主線程}}
注意:在使用多線程時,需要注意線程安全問題,如果程序中使用了共享變量,需要進行同步處理。
業(yè)務使用
@Override
public List<JSONObject> getBoomCrash(String appId, String androidEventType, String OS, Set<String> appVersionSet, List<Map<String, Long>> timeScope) throws URISyntaxException, IOException {Map<String, String[]> versionTagMap = new HashMap<>();// 首先獲取版本信息。業(yè)務代碼,省略....// 第一步先獲取傳入版本所有的crash數(shù)據(jù),并過濾掉版本首次出現(xiàn)的。業(yè)務代碼,省略List<BoomCrashDataVo> boomCrashDataList = ...// 第二步,獲取所有版本和UV【以昨日數(shù)據(jù)為標準,結(jié)果是UV倒序排列】。業(yè)務代碼,省略List<CrashVersionUvDataVo> versionUvResult = ...// 第三步,判斷當前版本的上一個全量版本。業(yè)務代碼,省略String lastVersion = ...List versionList = new ArrayList();for (String key : appVersionSet) {versionList.add(key);}versionList.add(lastVersion);String versionListstr = StringUtils.join(versionList, ",");List<JSONObject> boomCrashDataListNew = new ArrayList<>();// 第四步,循環(huán)判斷獲取某個issue數(shù)據(jù)的數(shù)量情況// Executors創(chuàng)建線程池new固定的10個線程ExecutorService taskExecutor = Executors.newCachedThreadPool();final CountDownLatch latch = new CountDownLatch(boomCrashDataList.size());//用于判斷所有的線程是否結(jié)束for (BoomCrashDataVo boomCrashData : boomCrashDataList) {Runnable run = new Runnable() {public void run() {try {// 這里是業(yè)務代碼...} finally {latch.countDown(); //每次調(diào)用CountDown(),計數(shù)減1}}};taskExecutor.execute(run);}try {//等待所有線程執(zhí)行完畢latch.await(); //主程序執(zhí)行到await()函數(shù)會阻塞等待線程的執(zhí)行,直到計數(shù)為0} catch (InterruptedException e) {e.printStackTrace();}taskExecutor.shutdown();// 按照TOP進行正序排序Collections.sort(boomCrashDataListNew, new Comparator<JSONObject>() {@Overridepublic int compare(JSONObject v1, JSONObject v2) {Integer uv1 = v1.getIntValue("topNumber");Integer uv2 = v2.getIntValue("topNumber");return uv1.compareTo(uv2);}});return boomCrashDataListNew;
}
改造成果
響應時間降到了20~30秒,和業(yè)務溝通在可接受范圍內(nèi)。同時,前端我修改成了在請求數(shù)據(jù)過程中顯示加載組件(參考antd的),這樣就不會顯示太過突兀,提升用戶使用體驗。
深入學習
執(zhí)行器服務
java.util.concurrent.ExecutorService 接口表示一個異步執(zhí)行機制,使我們能夠在后臺執(zhí)行任務。因此一個 ExecutorService 很類似于一個線程池。實際上,存在于 java.util.concurrent 包里的 ExecutorService 實現(xiàn)就是一個線程池實現(xiàn)。
ExecutorService executorService = Executors.newFixedThreadPool(10);executorService.execute(new Runnable() {public void run() {System.out.println("Asynchronous task");}});
executorService.shutdown();
首先使用 newFixedThreadPool() 工廠方法創(chuàng)建一個 ExecutorService。這里創(chuàng)建了一個十個線程執(zhí)行任務的線程池。然后,將一個 Runnable 接口的匿名實現(xiàn)類傳遞給 execute() 方法。這將導致 ExecutorService 中的某個線程執(zhí)行該 Runnable。
任務委派
下圖說明了一個線程是如何將一個任務委托給一個 ExecutorService 去異步執(zhí)行的:
一旦該線程將任務委派給 ExecutorService,該線程將繼續(xù)它自己的執(zhí)行,獨立于該任務的執(zhí)行。
ExecutorService實現(xiàn).
既然 ExecutorService 是個接口,如果你想用它的話就得去使用它的實現(xiàn)類之一。 java.util.concurrent 包提供了 ExecutorService 接口的以下實現(xiàn)類:
ThreadPoolExecutor
ScheduledThreadPoolExecutor
ExecutorService使用
有幾種不同的方式來將任務委托給 ExecutorService 去執(zhí)行:
- execute(Runnable)
- submit(Runnable)
- submit(Callable)
- invokeAny(…)
- invokeAll(…)
execute(Runnable)
execute(Runnable) 方法要求一個 java.lang.Runnable 對象,然后對它進行異步執(zhí)行。以下是使用 ExecutorService 執(zhí)行一個 Runnable 的示例:
ExecutorService executorService = Executors.newSingleThreadExecutor();
executorService.execute(new Runnable() {public void run() {System.out.println("Asynchronous task");}
});
executorService.shutdown();
沒有辦法得知被執(zhí)行的 Runnable 的執(zhí)行結(jié)果。如果有需要的話你得使用一個 Callable(以下將做介紹)。
submit(Runnable)
submit(Runnable) 方法也要求一個 Runnable 實現(xiàn)類,但它返回一個 Future 對象。這個Future 對象可以用來檢查 Runnable 是否已經(jīng)執(zhí)行完畢。
以下是 ExecutorService submit() 示例:
Future future = executorService.submit(new Runnable() {public void run() {System.out.println("Asynchronous task");}
});
future.get(); //returns null if the task has finished correctly
submit(Callable)
submit(Callable) 方法類似于 submit(Runnable) 方法,除了它所要求的參數(shù)類型之外。
Callable 實例除了它的 call() 方法能夠返回一個結(jié)果之外和一個 Runnable 很相像。
Runnable.run() 不能夠返回一個結(jié)果。Callable 的結(jié)果可以通過 submit(Callable) 方法返回的 Future 對象進行獲取。以下是一個
ExecutorService Callable 示例:
Future future = executorService.submit(new Callable(){public Object call() throws Exception {System.out.println("Asynchronous Callable");return "Callable Result";}
});
System.out.println("future.get() = " + future.get());// 輸出
Asynchronous Callable
future.get() = Callable Result
invokeAny()
invokeAny() 方法要求一系列的 Callable 或者其子接口的實例對象。調(diào)用這個方法并不會返回一個 Future,但它返回其中一個 Callable 對象的結(jié)果。無法保證返回的是哪個 Callable 的結(jié)果 - 只能表明其中一個已執(zhí)行結(jié)束。
如果其中一個任務執(zhí)行結(jié)束(或者拋了一個異常),其他 Callable 將被取消。
以下是示例代碼:
ExecutorService executorService = Executors.newSingleThreadExecutor();
Set<Callable<String>> callables = new HashSet<Callable<String>>();
callables.add(new Callable<String>() {public String call() throws Exception {return "Task 1";}
});
callables.add(new Callable<String>() {public String call() throws Exception {return "Task 2";}
});
callables.add(new Callable<String>() {public String call() throws Exception {return "Task 3";}
});
String result = executorService.invokeAny(callables);
System.out.println("result = " + result);
executorService.shutdown()
上述代碼將會打印出給定 Callable 集合中的一個的執(zhí)行結(jié)果
invokeAll()
invokeAll() 方法將調(diào)用你在集合中傳給 ExecutorService 的所有 Callable 對象。invokeAll() 返回一系列的 Future 對象,通過它們你可以獲取每個 Callable 的執(zhí)行結(jié)果。
記住,一個任務可能會由于一個異常而結(jié)束,因此它可能沒有 “成功”。無法通過一個 Future 對象來告知我們是兩種結(jié)束中的哪一種。
以下是一個代碼示例:
ExecutorService executorService = Executors.newSingleThreadExecutor();
Set<Callable<String>> callables = new HashSet<Callable<String>>();
callables.add(new Callable<String>() {public String call() throws Exception {return "Task 1";}
});
callables.add(new Callable<String>() {public String call() throws Exception {return "Task 2";}
});
callables.add(new Callable<String>() {public String call() throws Exception {return "Task 3";}
});
List<Future<String>> futures = executorService.invokeAll(callables);
for(Future<String> future : futures){System.out.println("future.get = " + future.get());
}
executorService.shutdown();
ExecutorService關(guān)閉
使用完 ExecutorService 之后你應該將其關(guān)閉,以使其中的線程不再運行。比如,如果你的應用是通過一個 main() 方法啟動的,之后 main 方法退出了你的應用,如果你的應用有一個活動的 ExexutorService 它將還會保持運行。ExecutorService 里的活動線程阻止了 JVM 的關(guān)閉。
要終止 ExecutorService 里的線程你需要調(diào)用 ExecutorService 的 shutdown() 方法。
ExecutorService 并不會立即關(guān)閉,但它將不再接受新的任務,而且一旦所有線程都完成了當前任務的時候,ExecutorService 將會關(guān)閉。在 shutdown() 被調(diào)用之前所有提交給ExecutorService 的任務都被執(zhí)行。
如果你想要立即關(guān)閉 ExecutorService,你可以調(diào)用 shutdownNow() 方法。這樣會立即嘗試停止所有執(zhí)行中的任務,并忽略掉那些已提交但尚未開始處理的任務。無法擔保執(zhí)行任務的正確執(zhí)行。可能它們被停止了,也可能已經(jīng)執(zhí)行結(jié)束。
最后感謝每一個認真閱讀我文章的人,禮尚往來總是要有的,雖然不是什么很值錢的東西,如果你用得到的話可以直接拿走:
這些資料,對于【軟件測試】的朋友來說應該是最全面最完整的備戰(zhàn)倉庫,這個倉庫也陪伴上萬個測試工程師們走過最艱難的路程,希望也能幫助到你!?