Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to process each product one by one with incremental progress update using Spring reactive?

I need help on Spring Reactive where a rest call posts list of Json objects and spring boot server should send the processing events one by one. Let me explain in brief with an example.

Let us take there are 20 products in the Front-end UI, user selects all the products to be processed. Each product processing takes minimum 1 min in the server side. Whenever each product is processed, server should send json message structure as event to the Front-end UI so that user will be able to see incremental progress of each product processing in the server.

In the UI , it should look like this.

Product 1 processed successfully

Product 2 processed successfully

Product 3 failed

like this.....

In the server side, the java code should be like this. Please suggest how to achieve using Spring Reactive.

public Flux<ProdModel> createAllCGs(List<Product> prodList) {

        for(Product p : prodList) {

            //Process here ...
        }

        //use Spring Reactor Flux

        //return Flux type object in the form of Json structure event not as Text Stream event.
    }

I know there are workarounds to achieve it using traditional polling mechanism or sending the product one by one. My question is more on Spring Reactive side where the rest call sends a bunch of products to be processed one by one by providing corresponding response in the json format to the UI side. I do not know whether it is possible or not. If you think it is not possible using Spring Reactive, that is also fine for me so that I can communicate to my architect who has suggested this.

like image 864
Sambit Avatar asked Jun 21 '19 10:06

Sambit


1 Answers

I struggled a bit to find out the answer,I an also new to Spring Reactive. I hope this answer will help to other.

I provide below the code snippet.

public Flux<ProdModel> createAllCGs(List<Product> prodList) {
      return Flux.fromIterable(prodList)
            .map(
                prodModel -> {
                  System.out.println("Input Data VM ::: " + prodModel);
                  return getProdModel(reviewModel);
                })
            .delayElements(Duration.ofSeconds(3));
    }

    private getProdModel getProdModel(ProdModel prodModel) {
        logger.debug("Time Now: {}", LocalDate.now());
        ProdModel cgModel = new CGModel();
        cgModel.setCgName("some Name");
        cgModel.setMessage("some meaningful message");
        cgModel.setTimestamp(LocalDateTime.now().toString());
        return cgModel;
  }

If you create a simple GET type rest end point and use the above method, you can see the output one by one after 3 seconds in the browser.

like image 88
Sambit Avatar answered Oct 21 '22 19:10

Sambit