多執行緒的應用(批量呼叫淘寶介面get圖片)
阿新 • • 發佈:2019-01-01
現狀
跟淘寶或天貓做商品對接的時候,需用到淘寶api提供taobao.picuture.get介面獲取淘寶圖片空間的商品圖片的url,我們在商品同步之前,首先需要批量通過sku去獲取所有sku的圖片連結,比如一個顏色sku就可能需要去get到如下這麼多圖片型別
,我們這邊業務同事一般都是批量輸入sku去get圖片連結,假設一次性20個sku獲取圖片連結 ,每個sku需要get大約15張圖片,大概就需要呼叫15*20 = 300 次get圖介面,這樣導致每次批量get圖片耗費的時間非常多,這樣會影響業務同事的體驗,浪費沒必要的時間,為了減少get圖過程中所耗費的時間,有兩種思路
1、採用多執行緒get圖
2、天貓支援批量get圖片介面
多執行緒get圖
通過實現Callable介面建立get圖片執行緒物件,核心程式碼如下
/***
* 根據13位sku獲取後臺圖片(採用Callable多執行緒,分批次呼叫get圖片介面,每次呼叫介面數:11) * @param sku * @return */ public List<Picture> getTaobaoPicturesByTitle(String sku){ //建立一個執行緒池 ExecutorService pool = Executors.newFixedThreadPool(TppConfig.DEFAULT_THREAD_MAX); List<Picture> list = new ArrayList<Picture>(); List<String> titles = getFixedTitleList(sku); List<List<String>> titleList = new ArrayList<List<String>>(); if(titleList.size() > 0){ for(List<String> tList:titleList){ List<Future> futures = new ArrayList<Future>(); for(String title:tList){ Callable callable = new PictureGetCallable(title,storeCode); //執行任務並獲取Future物件 Future future = pool.submit(callable); //從Future物件上獲取任務的返回值,並輸出到控制檯 futures.add(future); } if(futures.size() > 0){ for(Future f:futures){ try { list.addAll( (List<Picture>)f.get()); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } } } futures.clear(); } } //關閉執行緒池 pool.shutdown(); return list; } /**** * 內部類,get圖片執行緒類 * @author youqiang.xiong * */ public static class PictureGetCallable implements Callable<Object>{ private String title; private String storeCode; HashMap<String, String> condMap = new HashMap<String, String>(); public List<Picture> list = new ArrayList<Picture>(); public PictureGetCallable(String title,String storeCode){ this.title = title; this.storeCode = storeCode; } @Override public Object call() throws Exception { try{ condMap.clear(); condMap.put("title", title); TaobaoPictureListGet taobaoPictureListGet = new TaobaoPictureListGetImpl(storeCode); if(taobaoPictureListGet!=null){ List<Picture> pictures = taobaoPictureListGet.getTaobaoPictures(condMap); if(pictures.size() > 0 ){ list.addAll(pictures); } } }catch(Exception ex){ log.error("PictureGetCallable() title:"+title+" error.", ex); } return list; } }