Issue
I'm just starting to learn webFlux.I'm just starting to learn webplus and I'm interested in question.If it makes sense to use completableFuture together with CRUD operations?
That is , let 's say i have RestService
:
@RestController
@AllArgsConstructor
public class personController {
personServiceImpl personService;
@GetMapping("/all")
Flux<Person> getAllPerson(){
return personService.findAll();
}
@PostMapping("/save")
public Mono<Person> post(@RequestBody Person user) {
System.out.println("inside***************");
return personService.saveOrUpdate(user);
}
}
Does it make sense to make such a service for processing requests?
personServiceImpl:
public class personServiceImpl implements personService{
personRepository repository;
@Override
public Mono<Person> saveOrUpdate(Person person) {
CompletableFuture<Person> future = CompletableFuture.supplyAsync(() -> {
repository.save(person);
return person;
});
return Mono.fromFuture(future);
}
@Override
public Mono<Person> findByEmail(String email) {
CompletableFuture<Person> future = CompletableFuture.supplyAsync(() -> {
Person person = repository.findByEmail(email);
return person;
});
return Mono.fromFuture(future);
}
}
Or just regular calls without Future will work better?
public class personServiceImpl implements personService{
personRepository repository;
@Override
public Mono<Person> saveOrUpdate(Person person) {
return repository.save();
}
@Override
public Mono<Person> findByEmail(String email) {
return repository.findByEmail();
}
}
I will be glad if you can help me understand whether Future makes sense here .
Solution
In your case it does not make sense. WebFlux is already non-blocking which means that your application will be capable of handling other requests / processes while waiting for the Database to return the results of your query.
Future
s are more suited to very expensive processes that might take seconds or even minutes. In your cases, you are performing simple Database queries that should return a result within a few milliseconds so you are not really benefiting from the CompletableFuture
approach and it might even be counterproductive.
Just stick to WebFlux Mono
s and Flux
s and get rid of the CompletableFuture
approach. Start simple and do not try to optimize your code for no reason. Go with the simplest code you can implement that actually works and do not over-complicate it unless you really have the need.
Answered By - João Dias