2016-12-29 80 views
1

如果響應時間超過3秒,我想取消一個REST請求,但是我還沒有設法弄清楚該怎麼做。如果響應時間過長,則取消休息請求

所以我們可以說我有一個線程A:

@Override 
public void run() { 
    RestTemplate restTemplate = new RestTemplate(); 
    IsAliveMessage isAliveMessage = new IsAliveMessage(nodeInfo.getHostname(), nodeInfo.getPort()); 
    IsAliveResponse isAliveResponse = restTemplate.postForObject(
     "http://" + nodeInfo.getHostname() + ":" + nodeInfo.getPort() + "/node/isAlive", 
     isAliveMessage, 
     IsAliveResponse.class); 
} 

,使一個請求,我們期望爲B答案:

@RequestMapping(value="/isAlive", method= RequestMethod.POST) 
    public IsAliveResponse isAlive() throws ConnectException { 
     try { 
      Thread.sleep(100000); 
      IsAliveResponse response = new IsAliveResponse("here here!" ,true); 
      return response; 
     } catch (Exception e) { 
      Thread.currentThread().interrupt(); 
    } 
} 

B 「休眠」,不回答,但一不斷等待答案的到來。我怎樣才能讓A在一段時間後放棄等待?

在此先感謝

回答

1

您可以配置RestTemplate等待三秒這樣的迴應:

RestTemplate restTemplate = new RestTemplate(getClientHttpRequestFactory()); 

private ClientHttpRequestFactory getClientHttpRequestFactory() { 
    int timeout = 3000; 
    HttpComponentsClientHttpRequestFactory clientHttpRequestFactory = 
    new HttpComponentsClientHttpRequestFactory(); 
    clientHttpRequestFactory.setConnectTimeout(timeout); 
    clientHttpRequestFactory.setReadTimeout(timeout); 
    return clientHttpRequestFactory; 
} 
+0

謝謝,它的工作就像一個魅力 –

相關問題