How does Spring get the result from an endpoint that returns CompletableFuture object?

强颜欢笑 提交于 2021-02-07 20:25:23

问题


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));
    }
}

回答1:


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)

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



来源:https://stackoverflow.com/questions/58505549/how-does-spring-get-the-result-from-an-endpoint-that-returns-completablefuture-o

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!