![](/img/trans.png)
[英]How to intercept an AsyncClientHttpRequest using AsyncRestTemplate?
[英]How to increase timeout AsyncRestTemplate class?
我已经使用Spring框架和REST开发了一些异步Web服务,我从使用Spring类AsyncRestTemplate
创建的客户端中使用了它。 类返回一个对象ListenableFuture<ResponseEntity<T>>
(使用getForEntity
方法),该对象将带来Web服务返回的值(使用.get():<T>
)。 它工作正常,但是当Web服务花费大量时间时,即使Web服务尚未完成工作, ListenableFuture
类的isDone()
方法也将返回值true
。
如果我尝试使用客户端中的get()
方法恢复Web服务响应,并且时间已经很晚了,那么我总是会收到以下消息:
"timestamp": "2018-05-29T22:42:26.978+0000",
"status": 500,
"error": "Internal Server Error",
"message": "java.util.concurrent.ExecutionException: org.springframework.web.client.HttpServerErrorException: 503 null",
"path": "/client/result"
有人知道我该如何解决问题? 我希望客户端向我显示Web服务响应,即使Web服务花费很多时间(我想增加超时时间)也是如此。
服务器代码如下:
配置类别:
@Configuration
@EnableAsync
public class ConfigurationClass {
@Bean
public Executor threadPoolTaskExecutor() {
return new ThreadPoolTaskExecutor();
}
}
控制器类:
@RestController
@RequestMapping("/server")
public class ControllerClass {
@GetMapping("/start")
@Async
public CompletableFuture<String> callService() throws InterruptedException{
Thread.sleep(100000L);
return CompletableFuture.completedFuture("OK");
}
}
客户端代码(消费者)如下:
@RestController
@RequestMapping("/client")
public class ControllerClass {
private ListenableFuture<ResponseEntity<String>> entity;
@GetMapping("/start")
@Async
public void callService() throws InterruptedException {
AsyncRestTemplate restTemplate = new AsyncRestTemplate();
entity = restTemplate.getForEntity("http://localhost:8080/server/start",
String.class);
}
@GetMapping("/state")
public boolean getState() {
try {
return entity.isDone();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@GetMapping("/result")
public ResponseEntity<String> getResult() {
try {
return entity.get();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
我试图增加application.property文件中的属性超时,但是没有用。
# SPRING MVC (WebMvcProperties)
spring.mvc.async.request-timeout= 500000 # Amount of time before asynchronous request handling times out.
谢谢您的帮助,问候。
为了更好的维护,您可以配置AsyncRestTemplate bean:
@Bean
public AsyncRestTemplate asyncRestTemplate() {
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
factory.setTaskExecutor(new SimpleAsyncTaskExecutor());
factory.setConnectTimeout(1000);//milliseconds
factory.setReadTimeout(2000);//milliseconds
return new AsyncRestTemplate(factory);
}
然后,自动装配该bean:
@Autowired
private AsyncRestTemplate restTemplate;
之后,更新您的callService:
@GetMapping("/start")
public void callService() throws InterruptedException {
entity = restTemplate.getForEntity("http://localhost:8080/server/start",
String.class);
}
您可以删除@Async
注释,因为AsyncRestTemplate
是异步的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.