2012-06-04 57 views
1

我需要使用多線程環境實現HTTP連接池。我正在使用下面提到的代碼。提到的serviceURL需要大約1-3秒的響應時間,但是我從客戶端獲得每秒30-50次點擊。我需要點擊具有不同屬性的單個網址。所以我不清楚,我該如何迴應所有命中(30-40點/秒)。如果HttpURLConnection已經做了連接池,那麼多線程是它的解決方案。我怎麼能在JAVA中實現http連接池

我試圖用HTTPClient轉換這個程序,但不幸的是它不能正常工作。那麼你能告訴我如何使用多線程環境將此代碼轉換爲HTTPClient。

package airtel.product.action; 
import java.io.BufferedReader; 
import java.io.FileInputStream; 
import java.io.FileNotFoundException; 
import java.io.IOException; 
import java.io.InputStreamReader; 
import java.net.MalformedURLException; 
import java.net.URL; 
import java.security.KeyManagementException; 
import java.security.KeyStore; 
import java.security.KeyStoreException; 
import java.security.NoSuchAlgorithmException; 
import java.security.UnrecoverableKeyException; 
import java.security.cert.CertificateException; 

import javax.net.ssl.HostnameVerifier; 
import javax.net.ssl.HttpsURLConnection; 
import javax.net.ssl.KeyManagerFactory; 
import javax.net.ssl.SSLContext; 
import javax.net.ssl.SSLSession; 
import javax.net.ssl.SSLSocketFactory; 
import javax.net.ssl.TrustManager; 
import javax.net.ssl.TrustManagerFactory; 

import org.apache.commons.codec.binary.Base64; 

import java.util.logging.FileHandler; 
import java.util.logging.Level; 
import java.util.logging.LogManager; 
import java.util.logging.Logger; 
import java.util.logging.XMLFormatter; 
import java.util.Properties; 
import java.io.FileInputStream; 
import java.io.IOException; 


public class HTTPSClient { 
    public static void main(String[] args) { 
     try { 
      doHttpsPost("9711296535", "0.5", "0.5"); 
     } catch (MalformedURLException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } catch (Exception e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 

    } 
    private static HttpsURLConnection getHTTPSConnection(String url) throws Exception{ 
     URL chargingUrl; 

     HostnameVerifier hv = new HostnameVerifier(){ 
     public boolean verify(String urlHostName, SSLSession session) { 
     System.out.println("Warning: URL Host: "+urlHostName+" vs. "+session.getPeerHost()); 
     return true; 
     } 
     }; 
     HttpsURLConnection.setDefaultHostnameVerifier(hv); 
     KeyStore ks; 
     HttpsURLConnection urlc=null; 
     //try { 
      chargingUrl = new URL(url); 
      ks = KeyStore.getInstance("JKS"); 
      ks.load(new FileInputStream("/vishnu/twss/keystore/KEYSTORE.jks"), "12345678".toCharArray());//Location of keystore c:\\SDPKeystore.dat,12345678 
      KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); 
      kmf.init(ks, "[email protected]".toCharArray()); //password is [email protected] 
      TrustManager[] tm; 
      TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509"); 
      tmf.init(ks); 
      tm = tmf.getTrustManagers(); 
      SSLContext sslContext = SSLContext.getInstance("SSL"); 
      sslContext.init(kmf.getKeyManagers(), tm, null); 
      SSLSocketFactory sslSocketFactory =sslContext.getSocketFactory(); 
      urlc = (HttpsURLConnection) chargingUrl.openConnection(); 
      urlc.setSSLSocketFactory(sslSocketFactory); 
      //System.out.println("DoHttpPost(): Connection received"); 
      //System.out.println("DoHttpPost(): Setting UserName and Password");       
      String usernamePassword = "vishnu" + ":" + "[email protected]"; 
      String encoding = null; 

      byte[] encoded = Base64.encodeBase64(usernamePassword.getBytes()); 
      encoding = new String(encoded); 

      urlc.setRequestProperty("Authorization", "Basic " + encoding); 
      urlc.setRequestMethod("POST"); 
      urlc.setUseCaches(false); 
     return urlc; 
    } 

    public static HttpsURLConnection doHttpsPost(String msisdn, String actualPrice, String basePrice) throws MalformedURLException, Exception { 

    System.out.println("dHTTPPost(): Start"); 
    String chargingServiceURL="https://10.5.45.111:6443/sdpchargingservice/http/charge"; 
    String strResponse = ""; 
    HttpsURLConnection urlc=getHTTPSConnection(chargingServiceURL); 
    try{ 
     //get data from config file 
     Properties prop = new Properties(); 
     prop.load(new FileInputStream("/vishnu/twss/config.properties")); 

     System.out.println("HttpService :charge():Going to hit Charging Service.."); 
     Long currentMilis = System.currentTimeMillis(); 

     urlc.setRequestProperty("Keep-Alive", "300"); 
     urlc.setRequestProperty("Connection", "keep-alive"); 

     //set the keep aive in the system properties 
     System.setProperty("http.keepAlive", "true"); 
     System.setProperty("http.maxConnections", "2000"); 

     urlc.setRequestMethod("POST"); 
     urlc.setRequestProperty("SOAPAction",""); 
     urlc.setRequestProperty("Content-Type","text/xml; charset=utf-8"); 
     urlc.setDoOutput(true); 
     urlc.addRequestProperty("operation","debit"); 
     urlc.addRequestProperty("userId",msisdn); //CP to use his own msisdn 
     urlc.addRequestProperty("contentId","Exam Results"); 
     urlc.addRequestProperty("itemName","Exam Results"); 
     urlc.addRequestProperty("contentDescription", "Exam Results"+currentMilis); 
     urlc.addRequestProperty("contentMediaType","Exam Results"); 
     urlc.addRequestProperty("actualPrice",actualPrice); 
     urlc.addRequestProperty("basePrice",basePrice); 
     urlc.addRequestProperty("discountApplied","0"); 
     urlc.addRequestProperty("cpId","voicetap"); 
     urlc.addRequestProperty("eventType","Content Purchase"); 
     urlc.addRequestProperty("deliveryChannel","SMS"); 
     urlc.addRequestProperty("currency","INR"); 
     urlc.addRequestProperty("copyrightId","null"); 
     urlc.addRequestProperty("sMSkeyword","SMS"); 
     urlc.addRequestProperty("srcCode","606770"); 
     urlc.addRequestProperty("contentUrl","www.voicetap.com"); 
     urlc.addRequestProperty("copyrightDescription","Test Desc"); 
     System.out.println("going to hit service......"); 

     System.out.println(" urlc response "+urlc.getResponseMessage()); 

     try{  
      System.out.println(urlc.getHeaderField("status")); 
      String loggermsg = "MSISDN: "+prop.getProperty("userId") + 
        " Actualprice: "+prop.getProperty("actualPrice") + 
        " transactionId: "+urlc.getHeaderField("transactionId") + 
        " status: "+urlc.getHeaderField("status")+ 
        " errorCode: "+urlc.getHeaderField("errorCode")+ 
        " date: "+new java.util.Date(); 
      InputStreamReader isr = new InputStreamReader(urlc.getInputStream()); 
      BufferedReader in = new BufferedReader(isr); 
      String inputLine; 
      while ((inputLine = in.readLine()) != null){ 
      System.out.println(inputLine); 
      } 
      in.close(); 
     } 
     catch(Exception e){ 
      e.printStackTrace(); 
      System.out.println("Execption raised during parsing SOAP-response :::" + e.getMessage()); 
     } 
    } 
    catch (Exception ex) { 
     ex.printStackTrace(); 
     System.out.println("Error "+ex); 
    } 
    return urlc; 
} 
} 
+0

嗨tibo&Alex K我是堆棧溢出的新手。我沒有想過接受。感謝您的指導 – Vishnu

回答

0

HttpURLConnection已經做了連接池。除了避免調用dispose()之外,您無需執行任何操作。

+0

謝謝,那麼我該如何提高性能?我是否需要使用多線程環境。 – Vishnu

+0

@Vishnu我已經在你的標題中回答了這個問題。這是一個新問題,就像你關於HttpClient的第三個問題一樣。請下定決心。我不知道爲什麼你認爲多線程會有幫助,除非你連接到多個URL,如果你的問題中沒有出現這個URL,那麼這個URL是真的。 – EJP

+0

感謝EJP的寶貴意見。實際上面提到的serviceURL需要1.3秒來響應,但是我每秒鐘會得到約30-50次點擊。所以我不清楚,如何處理它。如果HttpURLConnection已經做了連接池,那麼多線程是它的解決方案嗎? Plz幫我 – Vishnu