How to Return a CompletableFuture in a RESTEasy Endpoint
1. Introduction This tutorial is all about using the CompletableFuture class in Quarkus RestEasy endpoints. 2. Asynchronous Endpoint in Sp...
1. Introduction
This tutorial is all about using the CompletableFuture class in Quarkus RestEasy endpoints.
2. Asynchronous Endpoint in Spring
Perhaps you are a Spring developer just like me who is used to asynchronous programming by chaining operations and results using CompletableFuture.
For example, if we have an endpoint for user registration that:
- Receive a DTO as input.
- Convert the DTO to POJO.
- Pass the POJO to the service layer
- Return a POJO.
- Convert the POJO to DTO.
- Return the POJO to the client caller.
@PostMapping(path = EndpointConstants.PATH_USER_REGISTRATIONS, produces = MediaType.APPLICATION_JSON_VALUE) @ResponseStatus(HttpStatus.OK) public CompletableFuture<RegisteredUserV1> registerUser(@Valid @RequestBody RegisterUserV1 user) { log.info("register user={}", user); return ssoService.registerUser(web2ServiceMapper.toUserPojo(user)) .thenApply(service2WebMapper::toUserDto); } // The userService @Override @Transactional public CompletableFuture<UserPojo> registerUser(UserPojo userPojo) { return CompletableFuture.completedFuture(new UserPojo()); }web2ServiceMapper and service2WebMapper are MapStruct interfaces that convert a DTO to POJO and vice versa.
3. Asynchronous Endpoint using RestEasy
RestEasy is a project that provides various frameworks to build RESTful web services. And this project is the one used in Quarkus, another Java framework similar to Spring. Instead of using @PostMapping (Spring), we used @Path/@POST annotations.
Let's convert the endpoint and service method that we have above.
@POST @Path(PATH_USER_REGISTRATIONS) public CompletableFuture<RegisteredUserV1> registerUser(@Valid RegisterUserV1 user, @Suspended final AsyncResponse asyncResponse) { log.info("register user={}", user); ssoService.registerUser(web2ServiceMapper.toUserPojo(user)) // converts to pojo .thenApply(service2WebMapper::toUserDto) // converts back to dto .thenApply(asyncResponse::resume); // async return }
The service method and mappers are the same in Spring. CompletableFuture is a Java class after all, and not from Spring or RestEasy/Quarkus.
Post a Comment