2013-10-14 3 views
1

Jetty 9 HttpClient API를 사용하여 높은로드 생성 비동기 HttpClient를 개발하려고합니다. POST 요청을 수행하는 기본 코드를 작성했습니다.Jetty 9 HttpClient를 사용한 비동기 POST 요청

public void connectHttp() throws Exception { 
    HttpClient client = new HttpClient();  
    // Configure HttpClient here 
    client.setMaxConnectionsPerDestination(1000);  

    try { 
     client.start(); 
    } catch(Exception e) { 
     System.out.println("Caught Exception in Client Start : "); 
     e.printStackTrace(); 
     throw e; 
    } 
    try { 
     for(int i = 0 ; i<1000;i++) { 
      client.POST("http://localhost:8080/privaterestservice/jersey/privatedata/writedata") 
      .timeout(3, TimeUnit.SECONDS) 
      .file(Paths.get("stats_kestrel.txt"),"text/plain").send(new BufferingResponseListener() { 
       @Override 
       public void onComplete(Result res) { 
        System.out.println("Got Response : "+res.isSucceeded()); 
             } 
      });   
     } 

    } 
    finally { 
     //client.stop(); 
    } 
    System.out.println("I am Done!!"); 
    System.out.println(client.getState()); 
} 

많은 요청으로 서버를 포격해야합니다. 하지만이 코드를 실행하면 마지막 몇 가지 요청에 실패합니다. Jmeter를 사용하여 검사했는데 서버에 문제가 없습니다. 또한 모든 요청이 완료된 후에도 코드가 중지되지 않습니다.

스레드가 슬립 상태가 아닌 모든 응답을받은 후 코드를 종료하는 방법은 무엇입니까?

은 어떤 도움이 크게 감사합니다 :)

+0

지난 몇 가지 요청으로 발생한 오류를 알려주십시오. 이 오류를 처리하고 로그 할 수 있습니다. –

+0

@AlexanderBezrodniy 지난 몇 가지 요청이 시간 초과로 인해 실패했습니다. 그냥 밖으로 발견하고 요청에 지정된 시간 제한을 제거하면 오류가 사라집니다. 이제 문제는 마지막 응답을받은 후에 스레드가 종료되는지 확인하는 것입니다. – Dinesh

답변

4

당신은 CountDownLatch를, 같은 것을 사용해야한다 : 모든 응답이 완료 때까지 기다릴 것

public void connectHttp() throws Exception { 
    HttpClient client = new HttpClient();  
    // Configure HttpClient here 
    client.setMaxConnectionsPerDestination(1000);  
    CountDownLatch countDown = new CountDownLatch(1000); 
    try { 
     client.start(); 
    } catch(Exception e) { 
     System.out.println("Caught Exception in Client Start : "); 
     e.printStackTrace(); 
     throw e; 
    } 
    try { 
     for(int i = 0 ; i<1000;i++) { 
      client.POST("http://localhost:8080/privaterestservice/jersey/privatedata/writedata") 
      .timeout(3, TimeUnit.SECONDS) 
      .file(Paths.get("stats_kestrel.txt"),"text/plain").send(new BufferingResponseListener() { 
       @Override 
       public void onComplete(Result res) { 
        System.out.println("Got Response : "+res.isSucceeded()); 
        countDown.countDown(); 
       } 

       @Override 
       public void onFailure(Response response, Throwable failure) { 
        countDown.countDown(); 
       } 
      });   
     } 

    } 
    finally { 
     //client.stop(); 
    } 
    countDown.await(); 
    System.out.println("I am Done!!"); 
    System.out.println(client.getState()); 
} 

합니다.

+0

감사합니다. @AlexanderBezrodniy. BufferingResponseListener를 별도의 파생 클래스로 작성하고 정적 변수를 사용하여 응답을 계산했습니다. – Dinesh

관련 문제