2016-06-28 27 views
3

我已經一個Apache HTTP客戶端定義如下:蝟:的Apache HTTP客戶機請求不中斷

private static HttpClient httpClient = null; 
HttpParams httpParams = new BasicHttpParams(); 
httpParams.setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, Boolean.TRUE); 
httpParams.setParameter(CoreProtocolPNames.USER_AGENT, "ABC"); 

HttpConnectionParams.setStaleCheckingEnabled(httpParams, Boolean.TRUE); 

SSLSocketFactory sf = SSLSocketFactory.getSocketFactory(); 

SchemeRegistry schemeRegistry = new SchemeRegistry(); 
schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory())); 
schemeRegistry.register(new Scheme("https", 443, sf)); 

//Initialize the http connection pooling 
PoolingClientConnectionManager connectionManager = new PoolingClientConnectionManager(schemeRegistry); 

// Initialize the connection parameters for performance tuning 
connectionManager.setMaxTotal(12); 
connectionManager.setDefaultMaxPerRoute(10); 

httpClient = new DefaultHttpClient(connectionManager, httpParams); 

我有一個錐命令play並已啓用了以下性質:

hystrix.command.play.execution.isolation.thread.timeoutInMilliseconds=1 
hystrix.command.play.execution.isolation.thread.interruptOnTimeout=true 

的命令本身的定義如下:

@HystrixCommand(groupKey="play_group",commandKey="play") 
    public String process(String request) throws UnsupportedOperationException, IOException, InterruptedException { 
     System.out.println("Before - process method : " + request); 
     callHttpClient(request); 
     System.out.println("After - process method" + request); 
     return ""; 
    } 

    private void callHttpClient(String request) throws ClientProtocolException, IOException, InterruptedException { 
     HttpGet get = new HttpGet("http://www.google.co.in"); 
     HttpResponse response = httpClient.execute(get); 
     System.out.println("Response:" + response); 
    } 

我現在試着執行命令5次循環:

public static void main(String[] args) throws UnsupportedOperationException, IOException, InterruptedException { 
     ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContextTest.xml"); 
     HystrixPlayground obj = ctx.getBean(HystrixPlayground.class); 

     long t1 = System.currentTimeMillis(); 
     for (int i = 0; i < 5; i++) { 
      try{ 
       System.out.println(obj.process("test" + i)); 
      } catch(Exception ex) { 
       System.out.println(ex); 
      } 
      long t2 = System.currentTimeMillis(); 
      System.out.println("Time(ms) : ---->" + (t2 - t1)); 

超時被設置爲1毫秒,因此處理方法引發HystrixRunTimeException。但是,http請求會繼續執行並顯示「After-process method」字符串。

我已經看到這種行爲一直只對http客戶端請求。如果http請求被線程休眠或非常大的for循環所替代,hystrix線程會按預期中斷。

有沒有人有任何洞察,爲什麼這可能會發生?

+0

請參閱https://stackoverflow.com/questions/20693335/how-can-i-catch-interruptedexception-when-making-http-request-with-apache –

回答

2

原因是中斷Java中的線程並不「強制停止」它。相反,調用Thread.interrupt()只需設置一個標誌,但不必由正在運行的線程解釋。查看更多這裏:What does java.lang.Thread.interrupt() do?

Apache HTTP客戶端不解釋此標誌。因此,HTTP請求不會被取消,只是完成。

相關問題