Apache HttpAsyncClient зависает на несколько секунд в случае высокой нагрузки - PullRequest
0 голосов
/ 28 октября 2018

В случае высокой нагрузки Apache HttpAsyncClient зависает на несколько секунд:

Я попытался создать диспетчер соединений с максимальным пулом из 200 соединений, а также устранил неактивные, просроченные соединения, выполнивотдельный выполняемый поток.

Вот фрагмент кода

public void init() {
        PoolingNHttpClientConnectionManager connectionManager = null;
        try {
            connectionManager = new PoolingNHttpClientConnectionManager (new DefaultConnectingIOReactor(IOReactorConfig.DEFAULT));
        } catch (IOReactorException e1) {

        }
        // Increase max total connection to 200
        connectionManager.setMaxTotal(200));
        // Increase default max connection per route to 20
        connectionManager.setDefaultMaxPerRoute(20);
        // Increase max connections for localhost:80 to 50
        HttpHost localhost = new HttpHost(127.0.0.1, 8080);
        int maxPerRoute = Integer.parseInt(20);
        connectionManager.setMaxPerRoute(new HttpRoute(localhost), maxPerRoute);
            client = HttpAsyncClients.custom()
                    .setConnectionManager((NHttpClientConnectionManager) connectionManager)
                    .build();

            client.start();

            try {
                url = new URL(httpParams.getUrlParam());
            } catch (MalformedURLException e) {
                e.printStackTrace();
            }               
    }

Выше метод будет вызываться при запуске сервера, ниже метод используется для инициации запроса.

private void invokePostMethodWithJsonContent(final JSONObject content, URL url2) throws HTTPException {

        HttpPost request = null;

        Future<HttpResponse> future = null;

        HttpResponse httpResp = null;


        String responseMsg = null;

        try {


            request = new HttpPost(url2.toString());            

            request.setEntity(new StringEntity(content.toString(), ContentType.APPLICATION_JSON));
            final RequestConfig requestConfig = RequestConfig.custom()
                    .setSocketTimeout(Integer.parseInt(httpParams.getReadTimeout()))
                    .setConnectTimeout(Integer.parseInt(httpParams.getConnectionTimeout()))
                    .setConnectionRequestTimeout(Integer.parseInt(httpParams.getReadTimeout())).build();

            request.setConfig(requestConfig);
            Long startTime = new Date().getTime();
            LOGGER.debug("time {}", new Date().getTime());

            future = client.execute(request, null);



            httpResp = (HttpResponse) future.get();

            if (httpResp != null && httpResp.getEntity() != null) {

                final HttpEntity responseEntity = httpResp.getEntity();

                if (responseEntity != null) {

                    responseMsg = EntityUtils.toString(responseEntity);


                }

            }


        } catch (final IOException e) {

            throw new HTTPException("Error in http adapter", "MPYHA00001", e);
        } catch (final JSONException e) {
            throw new HTTPException("Unable to process due to json error", "MPYHA00002", e);
        } catch (final InterruptedException e) {
            throw new HTTPException("Unable to connect http adapter", "MPYHA00003", e);
        } catch (final ExecutionException e) {

            throw new HTTPException("Error in http adapter", errorCode, e);

        } finally {
            httpResp = null;
            future = null;
            request = null;
        }

    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...