后端 同时请求多个第三方接口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 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> 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 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();
    }

}

 

你可能感兴趣的:(工具方法,接口,java,api)