我使用spring框架和REST开发了一些异步web服务,我从一个使用spring类AsyncRestTemplate创建的客户端使用它。类返回一个对象ListenableFuture<ResponseEntity<T>> (使用方法getForEntity),该对象返回web服务(使用方法.get():<T>)返回的值。它工作得很好,但是当web服务花费大量时间时,ListenableFuture类的方法isDone()会返回值true,即使web服务还没有完成工作。
如果我尝试在客户端使用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.谢谢你的帮助,致敬。
发布于 2019-01-30 18:05:50
为了更好地维护,您可以配置一个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是异步的。
https://stackoverflow.com/questions/50594022
复制相似问题