多线程的应用(批量调用淘宝接口get图片)

本文介绍了一种通过多线程技术优化批量获取淘宝商品图片的方法,以减少获取大量图片时所需的时间,提高业务效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

现状

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

        }


    }




### 使用多线程批量调用第三方 API 为了实现多线程批量调用第三方接口的功能,可以利用 Python 中的 `concurrent.futures` 模块中的 `ThreadPoolExecutor` 来管理多个线程。通过这种方式,可以在并发的情况下向第三方 API 发起请求。 以下是具体的实现方法以及代码示例: #### 多线程批量调用第三方 API 的核心逻辑 1. 创建一个函数用于发送 HTTP 请求到目标 API。 2. 将此函数封装在一个列表或其他可迭代对象中,以便传递给线程池执行器。 3. 使用 `ThreadPoolExecutor` 并发运行这些任务。 4. 收集所有返回的结果并处理它们。 下面是一个完整的代码示例[^1]: ```python import requests from concurrent.futures import ThreadPoolExecutor, as_completed def call_api(url): """ 调用单个 URL 的 API """ try: response = requests.get(url, timeout=5) response.raise_for_status() return {"url": url, "status_code": response.status_code, "result": response.json()} except Exception as e: return {"url": url, "error": str(e)} if __name__ == "__main__": urls = [ "https://api.example.com/data/1", "https://api.example.com/data/2", "https://api.example.com/data/3" ] with ThreadPoolExecutor(max_workers=5) as executor: # 设置最大工作线程数为 5 futures = [executor.submit(call_api, url) for url in urls] results = [] for future in as_completed(futures): # 获取已完成的任务结果 result = future.result() results.append(result) for res in results: if 'error' in res: print(f"Error calling {res['url']}: {res['error']}") # 打印错误信息 else: print(f"{res['url']} returned status code {res['status_code']} and data: {res['result']}") # 打印成功响应数据 ``` 上述代码展示了如何使用 `ThreadPoolExecutor` 实现多线程批量调用第三方 API,并收集每个请求的结果。如果某个请求失败,则会捕获异常并将错误信息记录下来。 #### 关于依赖项的安装 在实际开发环境中,可能还需要额外安装一些库来支持更复杂的场景(例如异步操作)。可以通过以下命令一次性安装所需的依赖包[^3]: ```bash pip install langchain langchain-openai langchain-core langchain-community langchain-experimental ``` 以上命令并非直接与本案例相关,但如果项目涉及自然语言处理或者链式调用等功能时,可能会需要用到类似的工具集合。 --- ###
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值