问题描述
在下面的代码中,当命中端点getPerson
时,响应将为Person类型的JSON.Spring如何将CompletableFuture<Person>
转换为Person
?
In the code below, when the endpoint getPerson
gets hit, the response will be a JSON of type Person.How does Spring convert CompletableFuture<Person>
to Person
?
@RestController
public class PersonController {
@Autowired
private PersonService personService;
@GetMapping("/persons/{personId}" )
public CompletableFuture<Person> getPerson(@PathVariable("personId") Integer personId) {
return CompletableFuture.supplyAsync(() -> personService.getPerson(personId));
}
}
推荐答案
返回CompletableFuture
时,它将触发Servlet 3.0异步处理功能,该功能将在其他线程中执行CompletableFuture
的执行,以便服务器可以尽快释放处理HTTP请求的线程以处理其他HTTP请求. (请参阅从此了解详细信息)
When the CompletableFuture
is returned , it triggers Servlet 3.0 asynchronous processing feature which the execution of the CompletableFuture
will be executed in other thread such that the server thread that handle the HTTP request can be free up as quickly as possible to process other HTTP requests. (See a series of blogpost start from this for detailed idea)
在@RestController
上注释的@ResponseBody
将使Spring通过 HttpMessageConverter 在内部注册.其实现之一是 MappingJackson2HttpMessageConverter ,它将进一步委托给Jackson,将Person
对象序列化为JSON字符串,并通过将其写入HttpServletResponse
The @ResponseBody
annotated on the @RestController
will cause Spring to convert the controller method 's retuned value (i.e Person
) through a HttpMessageConverter registered internally. One of its implementation is MappingJackson2HttpMessageConverter which will further delegate to the Jackson to serialise the Person
object to a JSON string and send it back to the HTTP client by writing it to HttpServletResponse
这篇关于Spring如何从返回CompletableFuture对象的端点获取结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!