后端 同时请求多个第三方接口api 方法

package util;

import com.google.common.collect.Lists;
import org.apache.commons.lang3.concurrent.BasicThreadFactory;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.web.util.UriUtils;

import java.io.IOException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

/**
 * @author admin
 */
public class MoreHttpApiDemo {
    /**
     * 请求接口
     */
    private static final List<String> API_URL = new ArrayList<>();

    private static ScheduledExecutorService pool = new ScheduledThreadPoolExecutor(10,
            new BasicThreadFactory.Builder().namingPattern("moreHttpApiDemo-pool-%d").daemon(Boolean.TRUE).build());

    static {
        API_URL.add("https://www.baidu.com/");
        API_URL.add("https://www.csdn.net/");
        API_URL.add("https://www.infoq.cn/");
    }

    private static void getMoreHttpApi() {
        List<Map<String, String>> returnMap = Lists.newArrayList();
        try {
            API_URL.forEach(url -> pool.submit(() -> {
                try {
                    returnMap.add(getHttp(url));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }));
            pool.shutdown();
            pool.awaitTermination(1, TimeUnit.HOURS);
            returnMap.forEach(map -> {
                String body = String.valueOf(map.values().toArray()[0]);
                System.out.println(body);
            });
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private static Map<String, String> getHttp(String url) throws IOException {
        HttpGet httpget = new HttpGet(new URL(UriUtils.encodePath(url, StandardCharsets.UTF_8.name())).toString());
        HttpEntity entity = null;
        try (var httpReturn = HttpClients.createDefault().execute(httpget)) {
            entity = httpReturn.getEntity();
            byte[] str = entity.getContent().readAllBytes();
            return new HashMap<>(1, 1f) {
                {
                    put(url, new String(str, StandardCharsets.UTF_8));
                }
            };
        } finally {
            EntityUtils.consumeQuietly(entity);
        }
    }

    public static void main(String[] args) {
        getMoreHttpApi();
    }

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值