首页 > 解决方案 > http响应没有返回503状态码-java中的多线程问题

问题描述

我正在使用具有固定线程池的执行器服务,该线程池提交未来的任务以创建 xml 文件。每次从 url 中获取 xml,生成 xml 并与现有的 xml 进行比较,以查找是否有任何不匹配。我提供了同步的 fetchAPIData 方法以使其线程安全 - 但它大大降低了性能。为了避免线程中断异常并使其线程安全,我在构建 httpclient 时设置了 connectionpoolmanager。我面临的问题是,当服务器达到 503 时,它会重新连接会话并重试连接。一旦 503 被击中,它会重试并发送响应,但程序似乎最终没有退出。似乎在无休止地等待来自某个线程响应的响应。以下是我的代码。我试过了

fetchAPIData:-

public String fetchAPIData(URI uri) throws ClarityAPIValidatorException {

        int retryCount = 0;
        CloseableHttpResponse httpResponse = buildHttpResponse(uri,
                getClientContext(), getHttpClient());

        int statusCode = httpResponse.getStatusLine().getStatusCode();
        try {
            switch (statusCode) {
                /*StatusCode - 200*/
                case HttpStatus.SC_OK:
                    return outputBasedOnStatusCode(httpResponse);
                /*StatusCode - 401*/
                case HttpStatus.SC_UNAUTHORIZED:
                    logger.info(ClarityAPIValidatorConstants.RESPONSE_CODE + httpResponse.getStatusLine().getStatusCode() + " " +
                            ClarityAPIValidatorConstants.URL + uri);
                    createSessionWithCookies(new URI(ClarityAPIProperties.getApiBaseURL()));
                    httpResponse = buildHttpResponse(uri, getClientContext(),
                            getHttpClient());
                    return outputBasedOnStatusCode(httpResponse);
                /*StatusCode - 503*/
                case HttpStatus.SC_SERVICE_UNAVAILABLE:

                        do {
                            logger.info(ClarityAPIValidatorConstants.RESPONSE_CODE + httpResponse.getStatusLine().getStatusCode() + " " +
                                    ClarityAPIValidatorConstants.URL + uri);
                            retryCount++;
                            this.pause(httpResponse, retryCount);
                            logger.info(ClarityAPIValidatorConstants.REQ_EXECUTING + uri);
                            createSessionWithCookies(uri);
                            httpResponse = buildHttpResponse(uri,
                                    getClientContext(), getHttpClient());
                            logger.info(ClarityAPIValidatorConstants.RETRY + ClarityAPIValidatorConstants.RESPONSE_CODE + httpResponse.getStatusLine().getStatusCode());

                        }
                        while (isRetryRequired(httpResponse, retryCount));
                        return outputBasedOnStatusCode(httpResponse);
                /*StatusCode other than 200, 401 and 503*/
                default:
                    throw new ClarityAPIValidatorException(UN_HANDLED_RES_TYPE +
                            statusCode + PATH + uri.getPath());
            }
        } catch (IOException | URISyntaxException e) {
            e.printStackTrace();
        }

        return null;
    }

创建会话cookie

 public void createSessionWithCookies(URI uri) throws ClarityAPIValidatorException {
        CredentialsProvider provider =
                buildCredentialsProvider(ClarityAPIProperties.getApiUsername(),
                        ClarityAPIProperties.getApiPassword());
        CloseableHttpClient httpClient = buildHttpClient(provider);
        HttpClientContext clientContext = buildHttpClientContext(uri, provider);

        if (httpClient == null || clientContext == null) {
            throw new ClarityAPIValidatorException(CREATE_SESSION_ERROR);
        } else {
            this.setHttpClient(httpClient);
            this.setClientContext(clientContext);
        }
    }

buildHttpClient :-

 public CloseableHttpClient buildHttpClient(CredentialsProvider provider) {
        RequestConfig requestConfig = RequestConfig.custom()
                .setCookieSpec(CookieSpecs.STANDARD)
                .build();
        PoolingHttpClientConnectionManager connManager =
                new PoolingHttpClientConnectionManager();
        
        return HttpClientBuilder.create()
                .setDefaultCredentialsProvider(provider)
                .setDefaultRequestConfig(requestConfig)
                .setConnectionManager(connManager)
                .build();
    }

buildHttpResponse:-

public  CloseableHttpResponse buildHttpResponse(URI uri,
                                                   HttpClientContext clientContext,
                                                   CloseableHttpClient httpClient)
            throws ClarityAPIValidatorException {

        HttpGet httpGet = buildHttpRequest(uri);
        CloseableHttpResponse response = null;

        try {
            response = httpClient.execute(httpGet, clientContext);
        } catch (IOException e) {
            e.printStackTrace();
            throw new ClarityAPIValidatorException(GET_REQ_FAIL + uri.getPath());
        }

        if (isNull(response))
            throw new ClarityAPIValidatorException(RES_NULL + uri.getPath());

        return response;
    }

isRetryRequired:- 最大重试次数为 5 次,时间为 5 秒、10 秒....最多 25 秒

 public boolean isRetryRequired(CloseableHttpResponse httpResponse,
                                   int retryCount) {
        return httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_SERVICE_UNAVAILABLE &&
                retryCount < ClarityAPIValidatorConstants.RETRY_MAX_COUNT;


    }

标签: javamultithreadinghttpclientexecutorservicehttp-status-code-503

解决方案


推荐阅读