Spring如何从返回CompletableFuture对象的端点获取结果? [英] How does Spring get the result from an endpoint that returns CompletableFuture object?

查看:644
本文介绍了Spring如何从返回CompletableFuture对象的端点获取结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的代码中,当命中端点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通过 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对象的端点获取结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆