Home > Software engineering >  Spring Boot Reactive: How to call the multiple services at the same time from performance optimizati
Spring Boot Reactive: How to call the multiple services at the same time from performance optimizati

Time:06-07

I am new to Spring Boot Reactive Microservices world, I've a below code which I am looking to call at the same time. Currently both the calls are blocked. How can we make the below code more performant?

@RestController
public class CustomerController {

    @Autowired
    private WebClient wc;

    @GetMapping("/servicestatus")
    public String getStatus() {
        return "up";
    }

    @RequestMapping(value="/customer/{cid}", method=RequestMethod.GET)
    public CustomerDetails getCustomer(@PathVariable String cid) {

        CustomerDetails customer = new CustomerDetails();
        //WebClient client = WebClient.create();

        ContactDetails svc1 = wc.get()
            .uri("http://localhost:8091/customer/"   cid   "/contactdetails")
            .retrieve()
            .bodyToMono(ContactDetails.class)
            .block();

        VehicleDetails svc2 = wc.get()
        .uri("http://localhost:8092/customer/"   cid   "/vehicledetails")
        .retrieve()
        .bodyToMono(VehicleDetails.class)
        .block();

        customer.setContactId(cid);
        customer.setContactName(svc1.getContactName());
        customer.setPostalCode(svc1.getPostalCode());
        customer.setLicensePlate(svc2.getLicensePlate());
        customer.setCarType(svc2.getCarType());

        return customer;

    }
}

CodePudding user response:

You should be able to something like this (although you should move service calls to another layer away from controllers). Just for demonstration:

@RequestMapping(value = "/customer/{cid}", method = RequestMethod.GET)
  Flux<CustomerDetails> getCustomer(@PathVariable String cid) {
    var fetchContactDetails = wc.get()
      .uri("http://localhost:8091/customer/"   cid   "/contactdetails")
      .retrieve()
      .bodyToMono(ContactDetails.class);

    var fetchVehicleDetails = wc.get()
      .uri("http://localhost:8092/customer/"   cid   "/vehicledetails")
      .retrieve()
      .bodyToMono(VehicleDetails.class);

    return Flux.zip(fetchContactDetails, fetchVehicleDetails)
      .parallel()
      .runOn(Schedulers.parallel())
      .map(result -> {
        CustomerDetails customer = new CustomerDetails();
        customer.setContactId(cid);
        customer.setContactName(result.getT1().getContactName());
        customer.setPostalCode(result.getT1().getPostalCode());
        customer.setLicensePlate(result.getT2().getLicensePlate());
        customer.setCarType(result.getT2().getCarType());
        return customer;
      })
      .sequential();
  }
  • Related