All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.kaizen4j.common.httpclient.AsyncHttpClientProxy Maven / Gradle / Ivy

There is a newer version: 1.3.8.RELEASE
Show newest version
package org.kaizen4j.common.httpclient;

import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpException;
import org.apache.http.HttpResponse;
import org.apache.http.HttpResponseInterceptor;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
import org.kaizen4j.common.util.JsonUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.Semaphore;

import static java.net.HttpURLConnection.HTTP_INTERNAL_ERROR;
import static java.net.HttpURLConnection.HTTP_OK;
import static java.nio.charset.StandardCharsets.UTF_8;

/**
 * 基于 NIO 的异步 HTTP 客户端代理类
 */
public class AsyncHttpClientProxy extends AbstractHttpClientProxy {

    private static final Logger logger = LoggerFactory.getLogger(AsyncHttpClientProxy.class);

    private CloseableHttpAsyncClient httpAsyncClient;

    private Semaphore concurrencyLock;

    private List httpResponseInterceptors;

    public AsyncHttpClientProxy(CloseableHttpAsyncClient httpAsyncClient, int maxConcurrencyCount) {
        this.httpAsyncClient = httpAsyncClient;
        this.concurrencyLock = new Semaphore(maxConcurrencyCount);
        this.httpResponseInterceptors = Lists.newArrayList();
    }

    public void addResponseInterceptor(HttpResponseInterceptor httpResponseInterceptor) {
        httpResponseInterceptors.add(httpResponseInterceptor);
    }

    @Override
    protected HttpResult request(HttpRequestBase httpRequestBase, Map requestHeader) {
        Preconditions.checkNotNull(httpRequestBase, "HttpRequestBase must be not null");

        String method = httpRequestBase.getRequestLine().getMethod();
        logger.info("Send {} request url: {}", method, httpRequestBase.getRequestLine().getUri());

        if (!CollectionUtils.isEmpty(requestHeader)) {
            requestHeader.forEach((name, value) -> httpRequestBase.setHeader(name, value));
            logger.info("Send {} request header: {}", method, JsonUtils.getJson(requestHeader));
        }

        HttpResult httpResult = new HttpResult();
        HttpContext httpContext = HttpClientContext.create();

        if (!httpAsyncClient.isRunning()) {
            httpAsyncClient.start();
        }

        try {
            concurrencyLock.acquireUninterruptibly();

            Future httpResponseFuture = httpAsyncClient.execute(httpRequestBase, httpContext, null);
            HttpResponse httpResponse = httpResponseFuture.get();

            // Http 响应拦截器处理
            for (HttpResponseInterceptor httpResponseInterceptor : httpResponseInterceptors) {
                httpResponseInterceptor.process(httpResponse, httpContext);
            }

            HttpEntity responseEntity = httpResponse.getEntity();
            if (Objects.nonNull(responseEntity) && HTTP_OK == httpResponse.getStatusLine().getStatusCode()) {
                httpResult.setBody(IOUtils.toString(responseEntity.getContent(), UTF_8));
            }

            httpResult.setStatus(httpResponse.getStatusLine().getStatusCode());
            /* 释放资源 */
            EntityUtils.consume(responseEntity);
        } catch (InterruptedException | ExecutionException | IOException | HttpException e) {
            httpResult.setStatus(HTTP_INTERNAL_ERROR);
            httpResult.setBody(e.getMessage());

            logger.error("Send request [" + httpRequestBase.getRequestLine().getUri() + "] failed", e);
        } finally {
            concurrencyLock.release();
            /* 释放资源 */
            httpRequestBase.releaseConnection();
        }

        return httpResult;
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy