在webservice

时间:2016-04-24 04:35:47

标签: java apache-httpclient-4.x tomee

我的Apache Http客户端代码存在问题。它是一个简单的hello world方法,另一个使用Apache http客户端代码调用hello world的方法。

我将它部署到webservice,对于前一个100左右的循环,它以20ms的快速响应时间。之后在响应时间慢慢开始上升,如果我运行3000次请求,响应时间变为150ms,10000 450ms等。此外,响应时间在经过长时间的活动后永远不会恢复,只会增加。

我已将其与方法createHttpClient相关联,b.build方法由于某种原因需要更长时间来构建客户端。有没有办法解决这个问题,或者是否有更好的http API用于长期条件。

我的代码(目前尚未最终确定概念验证阶段):

public final class HttpClientTools
{    
    private static Logger LOG = LoggerFactory.getLogger(HttpClientTools.class);

    private HttpClientTools() {}

    private static SSLContextBuilder ___builder = null;
    private static SSLContext sslContext = null;
    private static SSLConnectionSocketFactory __sslsf = null;
    private static Registry<ConnectionSocketFactory> socketFactoryRegistry = null;
    private static SSLConnectionSocketFactory sslsf = null;  
    private static final AllowAllHostnameVerifier allowAllHostnameVerifier = new org.apache.http.conn.ssl.AllowAllHostnameVerifier();

    private static void init() throws Exception
    {
        ___builder = SSLContexts.custom();    
        ___builder.loadTrustMaterial(null, new TrustStrategy() {
        public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { return true; }

        @Override
        public boolean isTrusted(java.security.cert.X509Certificate[] chain,String authType) throws CertificateException { return true; }
        });
        sslContext = ___builder.build();
        __sslsf = new SSLConnectionSocketFactory( sslContext, new String[] {"TLSv1", "TLSv1.1", "TLSv1.2"},null,new X509HostnameVerifier()
        {
                    @Override public void verify(String host, SSLSocket ssl) throws IOException { }
                    public void verify(String host, X509Certificate cert) throws SSLException { }
                    @Override public void verify(String host, String[] cns, String[] subjectAlts) throws SSLException { }
                    @Override public boolean verify(String s, SSLSession sslSession) { return true; }
                    @Override public void verify(String arg0,java.security.cert.X509Certificate arg1) throws SSLException { }
        });  
        socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory> create().register("http", PlainConnectionSocketFactory.INSTANCE).register("https", __sslsf).build();
        sslsf = new SSLConnectionSocketFactory(___builder.build());
    }    

    private static HttpClient createHttpClient(HttpClientToolsJsonInput input) throws Exception
    {
        HttpClientToolsInput temp = new HttpClientToolsInput();
        temp.setConnectionRequestTimeout(input.getConnectionRequestTimeout());
        temp.setConnectionTimeout(input.getConnectionTimeout());
        temp.setSocketTimeout(input.getSocketTimeout());
        temp.setUsername(input.getUsername());
        temp.setPassword(input.getPassword());
        temp.setUseDetailedResponseHandler(input.isUseDetailedResponseHandler());
        return HttpClientTools.createHttpClient(temp);
    }

    private static HttpClient createHttpClient(HttpClientToolsInput input) throws Exception
    {
        HttpClient rtn = null;
        long startms = System.currentTimeMillis();
        if (___builder == null)
        {
            init();
        }
        HttpClientBuilder b = HttpClientBuilder.create();
        b.setSslcontext( sslContext);
        HostnameVerifier hostnameVerifier = SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;     
        BasicHttpClientConnectionManager cm = new BasicHttpClientConnectionManager(socketFactoryRegistry);      
        b.setConnectionManager(cm);
        RequestConfig defaultRequestConfig = RequestConfig.custom().setSocketTimeout(
                input.getSocketTimeout()).setConnectTimeout(
                input.getConnectionTimeout()).setConnectionRequestTimeout(
                input.getConnectionRequestTimeout()).build();         
        b.setDefaultRequestConfig(defaultRequestConfig);
        if (StringTools.doesStringHaveData(input.getUsername()) && StringTools.doesStringHaveData(input.getPassword()) )
        {
            CredentialsProvider credsProvider = new BasicCredentialsProvider();
            credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(input.getUsername(), input.getPassword()));
            b.setDefaultCredentialsProvider(credsProvider);
        }
        long ms1=System.currentTimeMillis();     
        rtn = b.build(); // takes increasing time when deployed on tomee
        System.out.println("HttpClientTools m12 took "+(System.currentTimeMillis()-ms1)+" ms");
        long endms = System.currentTimeMillis();
        System.out.println("HttpClientTools getCloseableHttpClient() took "+(endms-startms)+" ms");            
        return rtn;
    }   

    public static String sendHttpPostRequest(HttpClientToolsInput input) throws Exception
    {
        HttpClient httpclient = null;   
        HttpPost _http = null;
        InputStream entityIS = null;
        String responseBody = null; 
        HttpResponse clhttpr = null;
        try
        {           
            for (String url : input.getUrls())
            {                           
                httpclient = HttpClientTools.createHttpClient(input);
                _http = new HttpPost(url);
                RequestConfig defaultRequestConfig = RequestConfig.custom().setSocketTimeout(input.getSocketTimeout()).setConnectTimeout(input.getConnectionTimeout()).setConnectionRequestTimeout(input.getConnectionRequestTimeout()).build();
                _http.setConfig(defaultRequestConfig);
                StringEntity strent = new StringEntity(input.getMessage());
                strent.setContentType("text/xml; charset=utf-8");
                _http.setEntity(strent);
                ResponseHandler<String> response = null;
                if (input.isUseDetailedResponseHandler())
                {
                    response = new DetailedExceptionReasonResponseHandler();
                }
                else
                {
                    response = new BasicResponseHandler();
                }
                boolean https = false;
                if (url.toLowerCase(Locale.US).startsWith("https"))
                {
                    https = true;
                }
                AuthCache authCache = new BasicAuthCache();
                BasicScheme basicAuth = new BasicScheme();
                HttpHost host = new HttpHost(url);
                if (StringTools.doesStringHaveData(input.getUsername()) && StringTools.doesStringHaveData(input.getPassword()))
                {
                    authCache.put(host, basicAuth);
                    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
                    credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(input.getUsername(), input.getPassword()));
                    HttpClientContext _context = HttpClientContext.create();
                    _context.setAuthCache(authCache);
                    _context.setCredentialsProvider(credentialsProvider);
                    clhttpr = httpclient.execute(_http, _context);
                }
                else
                {
                    clhttpr = httpclient.execute(_http);
                }
                entityIS = clhttpr.getEntity().getContent();
                responseBody = Convert.inputStreamToString(entityIS);
                try { EntityUtils.consume(_http.getEntity()); } catch(Exception e) {}   
                try { clhttpr.getEntity().getContent().close(); } catch(Exception e) {} 
                try { entityIS.close(); } catch(Exception e) {}                 
            }                   
            return responseBody;
        }
        catch (Exception e)
        {
            try { EntityUtils.consume(_http.getEntity()); } catch(Exception e1) {}  
            try { clhttpr.getEntity().getContent().close(); } catch(Exception e2) {}    
            try { entityIS.close(); } catch(Exception e3) {}    
            e.printStackTrace();
            throw e;
        }
    }

    public static void main(String[] args) throws Exception
    {
        HttpClientToolsInput input = new HttpClientToolsInput();
        input.setConnectionRequestTimeout(9000);
        input.setConnectionTimeout(9000);
        input.setSocketTimeout(9000);
        String msg2="<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:wsdl=\"http://myservice.org/wsdl\"><soapenv:Header/><soapenv:Body><wsdl:callHello/></soapenv:Body></soapenv:Envelope>";        
        input.setMessage(msg2);
        input.setUseDetailedResponseHandler(false);
        input.addUrl("http://127.0.0.1:8282/simple-webservice/MyService?wsdl");
        String response = "";
        long ms=0;
        for (int i=0; i<999;i++)
        {
            ms = System.currentTimeMillis();
            response = HttpClientTools.sendHttpPostRequest(input);
            System.out.println("response["+i+"][ms="+(System.currentTimeMillis()-ms)+"]="+response);
        }       
    }   
}

0 个答案:

没有答案