Reactive Programming using Spring MVC and WebFlux

Visualizing data - abstract purple background with motion blur, digital data analysis concept
Reading Time: 3 minutes

In this blog, we will learn about Reactive Programming using Spring WebMVC and WebFlux with examples.

Reactive Programming

It is a paradigm that used an asynchronous, non-blocking, event-driven approach to data processing. Reactive programming added modeling data and events to observe data streams and implemented data processing routines to react to the changes in those streams.

Spring MVC

Spring MVC is a Java framework that is used to build web applications. It follows the Model-View-Controller design pattern. It implements all the basic features of a core spring framework like Inversion of Control and Dependency Injection.

Spring WebFlux

Spring WebFlux is a non-blocking, annotation-based web framework. WebFlux uses Project Reactor and its publisher implementations, Flux, and Mono. WebFlux uses a router functions feature to apply functional programming to the web layer and bypass declarative controllers and Request Mapping.

It supports two programming models:

  • Annotation-based reactive components
  • Functional routing and handling

Spring boot application can be written as

  • Spring WebMVC(Imperative style) or
  • Spring WebFlux(Functional style).

What is Imperative style?

Imperative style is not like imperative programming, it is just a style of writing code. it means the Reactive application can be written using spring MVC annotations, so with minimum changes, the old, legacy, big applications can also be converted to reactive applications and can use its features and benefits.

What is Functional style?

The functional style is a programming style in which computations are codified as functional programming functions. These are mathematical function-like constructs (e.g. lambda functions) that are evaluated in expression contexts.

let’s see the example of Spring MVC and Spring Web Flux:-

Reactive Programming using Spring WebMVC and WebFlux
example of Reactive Programming using Spring WebMVC and WebFlux-

here we will use the same code on each model. here I have used the below bean and written a few GET/POST/DELETE Rest endpoints.

@Table

public class Student {

    @PrimaryKey

    private String id;

    private String name;

    private String course;

    private String collage;

}

REST endpoints in Spring Web-MVC:-


@RestController

@RequestMapping(path="/api")

public class StudentControllers {

	@Autowired StudentRepository studentRepository;

	@GetMapping(path="/student")

	public Flux<Student> getAll(){

		return studentRepository.findAll();

	}
	@GetMapping(path="/student/{id}")

	public Mono<Student> getById(@PathVariable("id") String id){

		return studentRepository.findById(id);
	}

	@PostMapping(path="/student")

	public Flux<Student> createBlogs(@RequestBody Flux<Student> blogs){

		return studentRepository.saveAll(blogs);

	}
	@DeleteMapping
	public Mono<Void> deleteById(@PathVariable("id") String id){

		return studentRepository.deleteById(id);

	}
}

REST endpoints in Spring WebFlux:-

@Configuration
public class StudentRouters {

    @Autowired
    StudentRepository studentRepository;

    @Bean

    public RouterFunction studentroute(){

        return RouterFunctions.nest(RequestPredicates.path("/api"),

                RouterFunctions.route(RequestPredicates.GET("/student"),

                        req-> 
ServerResponse.ok().body(studentRepository.findAll(),Student.class))

                .andRoute(RequestPredicates.GET("/student/id/{id}"),

                        req -> ServerResponse.ok().body(studentRepository.findById(req.pathVariable("id")),S

tudent.class))
             
   .andRoute(RequestPredicates.POST("/student"),

                     
   req -> 

ServerResponse.ok().body(studentRepository.saveAll(req.bodyToFlux(Student.cla

ss)),Student.class))

                
.andRoute(RequestPredicates.DELETE("/student/id/{id}"),

                       
 req -> 

ServerResponse.ok().body(studentRepository.deleteById(req.pathVariable("id")),Void.class))
        );
    }

}

so the above example is working with the combination of annotations and lambda functions.

For better reusability – the structure of code, we can have a dedicated handler and utility classes as Spring Component or Service.

Conclusion

In this blog, we learn about Reactive Programming using Spring WebMVC and WebFlux. in this article, we can see the Controller becomes Router. annotations become lambda functions, it may look like the Spring framework is moving towards lambda function-based configurations (XML → Annotations → lambda functions). in this blog, we learn how we can convert an MVC application to Spring Web Flux.

Written by 

I'm a Software Consultant at Knoldus Inc. I have done Post Graduation from Quantum University Roorkee. I have knowledge of various programming languages. I'm passionate about Java development and curious to learn Java Technologies. I'm always ready to learn new technologies and my hobbies are cricket and action movies.

Discover more from Knoldus Blogs

Subscribe now to keep reading and get access to the full archive.

Continue reading