温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

多线程调用第三方接口

发布时间:2020-06-28 02:35:45 来源:网络 阅读:737 作者:鲜鱼式 栏目:编程语言

最近刚刚做完一个新项目,记录分享一个批量调用第三方接口方法。相信有很多朋友在项目中都遇到过需要批量调用第三方接口,所以今天在这里分享一下,写的不好就多多指教。

首先,简单的介绍一下需求,判断一个电话号码的归属地,需要返回它的省份和城市。

   

       private List<String> getUpdateDataList(List<String> phoneList) {

// 创建线程池,这里创建了20个

ExecutorService executorService = Executors.newFixedThreadPool(20);

// 保存任务的返回结果

List<Future<String>> futureList = new ArrayList<>();

// 分配任务

for (String loopStr : phoneList) {

// 启动多线程返回号码的城市,有返回值使用submit(),并且多线程实现callable接口

Future<String> future = executorService

.submit(new UpdateCityThreadJob<String>(loopStr));

futureList.add(future);

}

// 关闭线程池

executorService.shutdown();

// 保存城市

List<String> collection = new ArrayList<>();

// 取出任务中的参数

for (Future<String> future : futureList) {

try {

// 取出任务中的结果

String city = future.get();

collection.add(city);

} catch (Exception e) {

throw new AppException(HttpStatus.INTERNAL_SERVER_ERROR);

}

}

return collection;

}


     // 创建任务类,因为有返回值,所以必须实现callable接口

public class UpdateCityThreadJob<V> implements Callable<String> {


        // 电话号码

private String phoneNumber;


public UpdateCityThreadJob(String phoneNumber) {

this.phoneNumber = phoneNumber;

}


/**

* @param phoneNumber 电话号码

* @return 城市

* @Description 获取 电话号码归属地邮政信息

*/

private String getCityRepeat(String phoneNumber) {

String city = "";

try {

city = getCity(phoneNumber);

} catch (Exception e) {

// 请求失败,重试五次,(防止网络原因导致请求失败)

for (int i = 0; i < 5; i++) {

try {

city = getCity(phoneNumber);

} catch (Exception e1) {

continue;

}

}

}

return city;

}


/**

* @Description 获取城市

* @param phoneNumber 电话号码

* @return 城市

* @throws Exception

*/

private String getCity(String phoneNumber) throws Exception {

// 请求第三方接口判断号码归属地

String result = HttpClient

.doGet("http://apis.juhe.cn/mobile/get?phone=" + phoneNumber + "&dtype=xml&key=" + Constants.API_KEY);

return result;

}


@Override

public String call() throws Exception {

synchronized (phoneNumber) {

                        

// 获取城市

String city = getCityRepeat(phoneNumber);

return city;

}

}


}


    调用第三放接口时,一般都会出现连接不稳定等等的异常,一般处理方式,都是重试几次即可。  

    代码是不是超级简单,只要思维清晰,什么问题都可以从容面对。。。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI