x Java Java 8 JUnit JSON
  • XML
  • JDBC Spring Boot Microservices React Contact Us

    Spring Boot WebFlux example

    Spring WebFlux which is a reactive-stack web framework, is fully non-blocking, supports Reactive Streams back pressure, and runs on such servers as Netty, Undertow, and Servlet 3.1+ containers.

    The term, "reactive", means instead of making some call and getting blocked till the response is received, processing will happen only when an event like mouse event, I/O event occurs.

    This example shows how to develop a simple reactive Spring Boot WebFlux application.

    Step 1) Create pom.xml

    Add spring-boot-starter-web and spring-boot-starter-webflux to pom.xml file.
        <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
        </dependency>	
    
        <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-webflux</artifactId>
        </dependency>	       

    Step 2) Create WebFluxApplication class

    When run, WebFluxApplication class will start the embedded Tomcat server and will have a preconfigured Spring MVC setup.

    package com.example.demo;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    
    @SpringBootApplication
    public class WebFluxApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(WebFluxApplication.class, args);
        }
    		
    }        

    Step 3) Create WebFluxController class

    Note that Flux is a return type, instead of plain String. Flux makes it reactive. If you want streaming response, you need to set produces = MediaType.TEXT_EVENT_STREAM_VALUE

    package com.example.demo;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.http.MediaType;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    import reactor.core.publisher.Flux;
    
    @RestController
    public class WebFluxController {
    	
        @Autowired
        private QuotesService quotesService;
    	
        @GetMapping(value = "/quotes", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
        public Flux<Quote> list() {
           return quotesService.quotes();
        }
       
    }      

    Step 4) Create Quote, QutesServiceImpl classes

    When run, WebFluxApplication class will start the embedded Tomcat server and will have a preconfigured Spring MVC setup.

    package com.example.demo;
    
    public class Quote {
    
        private long id;
        private String stock;
        private String type;
        private long currentPrice;
            
        public Quote(long id, String stock, String type, long currentPrice) {
            this.id = id;
            this.stock = stock;
            this.type = type;
            this.currentPrice = currentPrice;
        }
    
        public long getId() {
            return id;
        }
    
        public String getStock() {
            return stock;
        }
    
        public String getType() {
            return type;
        }
    
        public long getCurrentPrice() {
            return currentPrice;
        }
    
        @Override
        public String toString() {
            return "Quote [id=" + id + ", stock=" + stock + ", type=" + type
                    + ", currentPrice=" + currentPrice + "]";
        }
    	
    }        
    package com.example.demo;
    
    import reactor.core.publisher.Flux;
    
    public interface QuotesService {
    
        Flux<Quote> quotes();
    
    }        
    package com.example.demo;
    
    import java.time.Duration;
    import java.util.ArrayList;
    import java.util.Collection;
    
    import org.springframework.stereotype.Service;
    
    import reactor.core.publisher.Flux;
    
    @Service
    public class QutesServiceImpl implements QuotesService {
    	
        private final Collection<Quote> quotes =  new ArrayList<>();
        
        public QutesServiceImpl() {
        	quotes.add(new Quote(123, "Microsoft", "BUY" , 100));
        	quotes.add(new Quote(124, "Microsoft", "BUY" , 101));
        	quotes.add(new Quote(125, "Microsoft", "BUY" , 102));
        	quotes.add(new Quote(126, "Microsoft", "BUY" , 103));
        	quotes.add(new Quote(127, "Microsoft", "BUY" , 104));
        	quotes.add(new Quote(128, "Microsoft", "BUY" , 105));
        	quotes.add(new Quote(129, "Microsoft", "BUY" , 106));
        }
    
        @Override
        public Flux<Quote> quotes() {
            return Flux.fromIterable(quotes).delayElements(Duration.ofMillis(500));
        }
    
    	
    }
            

    Directory structure

    Directory structure











    Step 5) Run WebFluxApplication

    Console Output :

     
    2019-12-07 12:42:40.765  INFO 4044 --- [main] com.example.demo.WebFluxApplication      : Starting WebFluxApplication on ssss-PC with PID 4044 (C:\Dev\eclipse\workspace\SpringBoot\target\classes started by sss in C:\Dev\eclipse\workspace\SpringBoot)
    2019-12-07 12:42:40.769  INFO 4044 --- [main] com.example.demo.WebFluxApplication      : No active profile set, falling back to default profiles: default
    2019-12-07 12:42:42.681  INFO 4044 --- [main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.21]
    2019-12-07 12:42:42.839  INFO 4044 --- [main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
    2019-12-07 12:42:42.839  INFO 4044 --- [main] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 1961 ms
    2019-12-07 12:42:43.395  INFO 4044 --- [main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
    2019-12-07 12:42:43.909  INFO 4044 --- [main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
    2019-12-07 12:42:43.913  INFO 4044 --- [main] com.example.demo.WebFluxApplication      : Started WebFluxApplication in 3.746 seconds (JVM running for 4.29)   

    Step 6) Testing WebFluxApplication

    Open any browser and launch http://localhost:8080/quotes. You will see streaming quotes displayed in the broswer.


    Web Flux








    Web Flux


















    References :

    Spring WebFlux

    Comments

    Leave a Reply

    Your email address will not be published. Required fields are marked *











    Share This