现状
跟淘宝或天猫做商品对接的时候,需用到淘宝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;
}
}