2017-02-16 55 views
5

我使用Spring 4.2.3 AsyncRestTemplate.exchange()調用一些API,將採取幾秒鐘,我期待的是listenableFuture.get(1,TimeUnit.SECONDS)將塊1秒,然後拋出TimeOutException。阻斷對ListenableFuture與超時

代替會發生什麼情況是,listenableFuture.get()將API調用的整個時間(超過1秒)塊

AsyncRestTemplate restTemplate = new AsyncRestTemplate(); 

    ListenableFuture<ResponseEntity<String>> listenableFuture = restTemplate.exchange(URL, HttpMethod.GET, null, String.class); 
    log.debug("before callback"); 

    //...add callbacks 

    try{ 
     log.debug("before blocking"); 
     listenableFuture.get(1, TimeUnit.SECONDS); 
    }catch (InterruptedException e) { 
     log.error(":GOT InterruptedException"); 
    } catch (ExecutionException e) { 
     log.error(":GOT ExecutionException"); 
    } catch (TimeoutException e) { 
     log.info(":GOT TimeoutException"); 
    } 

    log.info("FINISHED"); 

輸出:

09:15:21.596 DEBUG [main] org.springframework.web.client.AsyncRestTemplate:78 - Created asynchronous GET request for "http://localhost:4567/oia/wait?seconds=5" 
    09:15:21.666 DEBUG [main] org.springframework.web.client.RestTemplate:720 - Setting request Accept header to [text/plain, application/xml, text/xml, application/json, application/*+xml, application/*+json, */*] 
    09:15:21.679 DEBUG [main] com.zazma.flow.utils.FutureTest:74 - before callback 
    09:15:21.679 DEBUG [main] com.zazma.flow.utils.FutureTest:95 - before blocking 
    09:15:26.709 DEBUG [main] org.springframework.web.client.AsyncRestTemplate:576 - Async GET request for "http://localhost:4567/oia/wait?seconds=5" resulted in 200 (OK) 
    09:15:26.711 DEBUG [main] org.springframework.web.client.RestTemplate:101 - Reading [java.lang.String] as "text/html;charset=utf-8" using [[email protected]44431a] 
    09:15:26.717 INFO [main] com.zazma.flow.utils.FutureTest:105 - FINISHED 

下面是一個例子ListenableFuture.get()將在未由AsyncRestTemplate創建時按預期工作

SimpleAsyncTaskExecutor te = new SimpleAsyncTaskExecutor(); 
    ListenableFuture<String> lf = te.submitListenable(() -> { 
     Thread.sleep(8000); 
     return "OK"; 
    }); 

    lf.get(1, TimeUnit.SECONDS); 
+0

爲什麼它說:「等待?秒= 5」在日誌中的第5行的網址是什麼? –

+0

@vstromcoder我創建的本地的API,讓X作爲號碼並等待X秒鐘,然後返回OK。所以我傳遞給交易所的網址是API。這就是爲什麼我試圖在API完成之前等待1秒(5秒後) – Yoni

回答

1

Yo你的代碼是完全正確的。造成問題的原因是春季框架中的一個錯誤。雖然,我沒發現它在春天的問題跟蹤器(也可能是它沒有記錄),您可以通過更新依賴固定。當然,你的代碼可以使用spring-web> = 4.3.2.RELEASE的版本。