我有以下场景:我设置了一个客户端,它向服务器发送一个异步HTTP请求。客户端接收到一个CompletableFuture。到目前为止,一切工作正常。但是,我无法访问我发送的请求的响应。
completableFuture.get().body()
而是包含请求的状态。更详细地说,
{"cancelled":false,"done":true,"completedExceptionally":false,"numberOfDependents":0}
我怎样才能得到真实的结果?
这是我的代码...
休息控制器
@RestController
public class WorkerJController {
@Autowired
private WorkerJService service;
@GetMapping(value = "/JobList", produces = MediaType.APPLICATION_JSON_VALUE)
public CompletableFuture<ResponseEntity> getJobListFunction() throws JsonProcessingException, InterruptedException {
return CompletableFuture.completedFuture(service.getJobListFunction()).thenApply(ResponseEntity::ok);
}
}
服务
@Service
public class WorkerJService {
public static ArrayList<someThing> randomList = new ArrayList<>();
@Async
public CompletableFuture<String> getJobListFunction() throws JsonProcessingException, InterruptedException {
randomList.add(new someThing("abc", "dfe"));
ObjectMapper mapper = new ObjectMapper();
TimeUnit.SECONDS.sleep(5);
return CompletableFuture.completedFuture(mapper.writeValueAsString(jobList));
}
}
异步配置
@Configuration
@EnableAsync
public class AsyncConfig {
@Bean(name = "taskExecutor")
public Executor taskExecutor(){
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(3);
executor.setMaxPoolSize(3);
executor.setQueueCapacity(100);
executor.setThreadNamePrefix("AsynchThread-");
executor.initialize();
return executor;
我发送HTTP请求如下:
HttpClient client = HttpClient.newBuilder()
.version(HttpClient.Version.HTTP_1_1)
.followRedirects(HttpClient.Redirect.NORMAL)
.connectTimeout(Duration.ofSeconds(20))
.build();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("http://localhost:8080/JobList"))
.timeout(Duration.ofMinutes(2))
.GET()
.build();
CompletableFuture<HttpResponse<String>> cf = client
.sendAsync(request, HttpResponse.BodyHandlers.ofString());
1条答案
按热度按时间6kkfgxo01#
CompletableFuture.completedFuture(service.getJobListFunction())
会将service.getJobListFunction()
传回的CompletableFuture
Package 成另一个CompletableFuture
。只需将来自服务的响应直接与
thenApply()
链接起来即可: