Monty  Boehm

Monty Boehm

1671443609

How to Reactive Programming using Spring MVC and WebFlux

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.

Original article source at: https://blog.knoldus.com/

#webflux #spring #mvc 

How to Reactive Programming using Spring MVC and WebFlux
Bongani  Ngema

Bongani Ngema

1671175223

Learn Router Function in Spring Webflux

In Spring WebFlux, router functions are used to route requests to the corresponding HandlerFunction. Typically, you don’t write router functions yourself, but use a method in the RouterFunctions handler class to create them. RouterFunctions.route() (with no parameters) gives you a fluent constructor to create a router function, while RouterFunctions.route(RequestPredicate, HandlerFunction) gives you a direct way to create a router.

It is generally recommended to use the route() constructor as it provides convenient shortcuts for
typical mapping scenarios without the need for hard-to-detect static imports. For example,
the router function builder provides a GET(String, HandlerFunction) method to create the mapping
GET requests; and POST(String, HandlerFunction) for POST.

In addition to mapping based on the HTTP method, the route builder offers a way to introduce others
predicates when mapping to requests. For every HTTP method, there is an overloaded variant that takes a RequestPredicate as a parameter, although other restrictions can be expressed.

Predicates

You can write your own RequestPredicate, but the RequestPredicates handler class is commonly provided
implementation used based on request path, HTTP method, content type, and so on. The following example uses the requested predicate to create a constraint based on the Accept header:

Java:

RouterFunction<ServerResponse> route = RouterFunctions.route()

.GET("/hello-world", accept(MediaType.TEXT_PLAIN),

request -> ServerResponse.ok().bodyValue("Hello World")).build();

Kotlin:

val route = coRouter {

GET("/hello-world", accept(TEXT_PLAIN)) {

ServerResponse.ok().bodyValueAndAwait("Hello World")

}

}

You can compose multiple request predicates together by using:

  • RequestPredicate.and(RequestPredicate) — both must match.
  • RequestPredicate.or(RequestPredicate) — either can match.

Many of the predicates RequestPredicates.GET(String) from is RequestPredicates composed of are
composed. For example, RequestPredicates.method(HttpMethod) and RequestPredicates.path(String). The above example also uses two request predicates because the constructor uses RequestPredicates.GET internally and composes them with the accepted predicate.

Routes

Router functions are evaluated in order: if the first route does not match, the second is evaluated,
and so on. Therefore, it makes sense to declare more specific routes before general ones. It is also
important when registering router functions as Spring beans, as described later. Note that this behavior differs from the annotation-based programming model, where the “most specific” controller method is automatically selected.

When using the router function builder, all defined routes are folded into a single RouterFunction
which is returned from the build(). There are also other ways to build more router features
together:

  • add(RouterFunction) on the RouterFunctions.route() builder
  • RouterFunction.and(RouterFunction)
  • RouterFunction.andRoute(RequestPredicate, HandlerFunction) — shortcut for RouterFunction.and() with nested RouterFunctions.route().

The following example shows the composition of four routes:

Java:

import static org.springframework.http.MediaType.APPLICATION_JSON;

import static org.springframework.web.reactive.function.server.RequestPredicates.*;

PersonRepository repository = ...

PersonHandler handler = new PersonHandler(repository);

RouterFunction<ServerResponse> otherRoute = ...

RouterFunction<ServerResponse> route = route()

   .GET("/person/{id}", accept(APPLICATION_JSON), handler::getPerson) ①

   .GET("/person", accept(APPLICATION_JSON), handler::listPeople) ②

   .POST("/person", handler::createPerson) ③

   .add(otherRoute) ④

   .build();
  1. GET /person/{id} with an Accept header that matches JSON is routed to PersonHandler.getPerson
  2. GET /person with an Accept header that matches JSON is routed to PersonHandler.listPeople
  3. POST /person with no additional predicates is mapped to PersonHandler.createPerson, and
  4. otherRoute is a router function that is created elsewhere and added to the route built.

Kotlin:

import org.springframework.http.MediaType.APPLICATION_JSON

val repository: PersonRepository = ...

val handler = PersonHandler(repository);

val otherRoute: RouterFunction<ServerResponse> = coRouter {  }

val route = coRouter {

    GET("/person/{id}", accept(APPLICATION_JSON), handler::getPerson) 

    GET("/person", accept(APPLICATION_JSON), handler::listPeople)
 
    POST("/person", handler::createPerson) 

}.and(otherRoute) 
  1. GET /person/{id} with an Accept header that matches JSON is routed to PersonHandler.getPerson
  2. GET /person with an Accept header that matches JSON is routed to PersonHandler.listPeople
  3. POST /person with no additional predicates is mapped to PersonHandler.createPerson, and
  4. otherRoute is a router function that is created elsewhere and added to the route built.

Nested Routes

It is common for a group of router functions to have a shared predicate, such as a shared path.
In the example above, the shared predicate would be the path predicate that matches /person, used
in three ways. When using annotations, you would remove this duplication by using type-
level of the @RequestMapping annotation that maps to /person.

In WebFlux.fn, path predicates can be shared via the path method in the router function builder. For example, the last few lines of the above example can be improved as follows using nested routes:

Java:

RouterFunction<ServerResponse> route = route()

    .path("/person", builder -> builder ①

        .GET("/{id}", accept(APPLICATION_JSON), handler::getPerson)

        .GET(accept(APPLICATION_JSON), handler::listPeople)

        .POST(handler::createPerson))

    .build();

Note that the second parameter of the path is a consumer that takes the router builder.

Kotlin:

val route = coRouter {

    "/person".nest {

        GET("/{id}", accept(APPLICATION_JSON), handler::getPerson)

        GET(accept(APPLICATION_JSON), handler::listPeople)

        POST(handler::createPerson)

    }

}

Although path-based nesting is the most common, you can nest on any kind of predicate using
the nest method on the builder. The above still contains some duplication in the form of the shared receive header predicate. We can improve further by using the nesting method along with adopting:

Java:

RouterFunction<ServerResponse> route = route()

    .path("/person", b1 -> b1

        .nest(accept(APPLICATION_JSON), b2 -> b2

            .GET("/{id}", handler::getPerson)

            .GET(handler::listPeople))

        .POST(handler::createPerson))

    .build();

Kotlin:

val route = coRouter {

    "/person".nest {

        accept(APPLICATION_JSON).nest {

            GET("/{id}", handler::getPerson)

            GET(handler::listPeople)

            POST(handler::createPerson)

        }

    }

}

Conclusion:

In conclusion, in this blog, we have learned about Router Functions in Spring WebFlux. I will be covering more topics on Spring Webflux in my future blogs, stay connected. Happy learning 🙂

For more, you can refer to the WebFlux documentation: https://docs.spring.io/spring-framework/docs/current/reference/html/web-reactive.html

For a more technical blog, you can refer to the Knoldus blog: https://blog.knoldus.com/

Original article source at: https://blog.knoldus.com/

#spring #webflux #function 

 Learn Router Function in Spring Webflux
Rupert  Beatty

Rupert Beatty

1671106023

Getting Started with Spring Web-flux

Spring Boot provides very good support for building RESTful Web Services for enterprise applications. This blog will explain building RESTful web services using Spring Boot in detail with a pinch of reactive programming using web flux. I will mostly be walking through the code snippets which we can use to quickly start with the web flux without having to dive deep. It is like a code-first approach.

Start with Build

If you are using Maven, use the following code to add the below dependency in your pom.xml file −

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" 

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

		 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 

https://maven.apache.org/xsd/maven-4.0.0.xsd">

	<modelVersion>4.0.0</modelVersion>

	<parent>

		<groupId>org.springframework.boot</groupId>

		<artifactId>spring-boot-starter-parent</artifactId>

		<version>2.6.9</version>

		<relativePath/> <!-- lookup parent from repository -->

	</parent>

	<groupId>com.webflux</groupId>

	<artifactId>demo-webflux</artifactId>

	<version>0.0.1-SNAPSHOT</version>

	<name>demo-webflux</name>

	<description>Demo project for Spring Boot</description>

	<properties>

		<java.version>11</java.version>

	</properties>

	<dependencies>

		<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>


		<dependency>

			<groupId>org.springframework.boot</groupId>

			<artifactId>spring-boot-starter-test</artifactId>

			<scope>test</scope>

		</dependency>

		<dependency>

			<groupId>io.projectreactor</groupId>

			<artifactId>reactor-test</artifactId>

			<scope>test</scope>

		</dependency>

		<dependency>

			<groupId>org.springframework.boot</groupId>

			<artifactId>spring-boot-starter-data-
mongodb</artifactId>

		</dependency>

		<dependency>

			<groupId>org.springframework.boot</groupId>

			<artifactId>spring-boot-starter-data-mongodb-
reactive</artifactId>

		</dependency>

	</dependencies>

	<build>

		<plugins>

			<plugin>

				<groupId>org.springframework.boot</groupId>


				<artifactId>spring-boot-maven-
plugin</artifactId>

			</plugin>

		</plugins>

	</build>

</project>

Code Implementation

REST CONTROLLER
We use the @RestController annotation to define the RESTful web services. It serves JSON, and custom responses.

@RestController

public class AnimalController {

}


The default HTTP request method is GET. This method does not require any Request Body. The request URI is /animalByName and it will return the value stored.

@GetMapping("/animalByName")

    public ResponseEntity<Flux<Animal>> findAnimalByName(){

        return new ResponseEntity<Flux<Animal>>

(animalService.findAnimalByName(), new HttpHeaders() ,HttpStatus.OK);

    }


The HTTP(Hypertext transfer protocol) POST request is used to create a resource. This method contains the Request Body. The request URI is /add, and it will return the value after adding a new animal name into the database.
 

    @PostMapping("/add")

    public ResponseEntity<Mono<Animal>> saveDataIntoDatabase(@RequestBody 

Animal animal){

        return new ResponseEntity<Mono<Animal>>

(animalService.saveDataIntoDatabase(animal) , new HttpHeaders() , 

HttpStatus.OK);

    }
    

Mono and Flux

Spring Webflux uses Project Reactor as the reactive library. Spring WebFlux heavily uses 2 publishers:

Mono: Returns zero or one part.
Flux: Returns 0…N components.
The reactor may be a Reactive Streams library and, therefore, all of its operators support non-blocking back-pressure. Reactor features a sturdy specialization in server-side Java. WebFlux needs Reactor as a core dependency however it’s practical with different reactive libraries via Reactive Streams.

What is Mono? Why do we use Mono?
Mono may be a Reactive Streams Publisher with basic operators that complete with success.
Let’s explore some features of Flux/Mono that facilitate to filter, transforming, and mixing of the Publisher stream
Filter the supply against the given predicate victimization the filter technique.

What is Flux? Why do we use Flux?
Flux could be a Reactive Stream Publisher with basic operators that emit zero to N components and then complete (successfully or with associate error).
The subscribe technique is employed to subscribe a client to the Flux that may consume all the weather within the sequence, similar to a client that may handle errors. you’ll concatenate emissions of this Flux with the provided Publisher exploitation of the concatWith technique. On invoking the error technique, Flux is formed that terminates with the desired error instantly when being signed.

Now we are going to create our main application classwebfluxexample.java

package com.knoldus.webfluxexample;


@EnableMongoRepositories

@EnableReactiveMongoRepositories

@SpringBootApplication

public class SpringWebfluxExampleApplication {


	public static void main(String[] args) {

		SpringApplication.run(SpringWebfluxExampleApplication.class, 

args);

	}

}

After the main application class, we will make the Controller class – animalcontroller.java

package com.knoldus.webfluxexample.controller;

@RestController

@RequestMapping("/animal")

public class AnimalController {

	@Autowired

    private final AnimalService animalService;

    public AnimalController(AnimalService animalService){

        this.animalService= animalService;

    }

}

After the controller class, we have to store our data so to store our data we will make an entity class – animal.java
In this class, we will define what data/value we want to store in our database

package com.knoldus.webfluxexample.entity;

@Document(collection = "Animal")

public class Animal {

@Id

private int id;

private String name;

private String address;

    public int getId() {

        return id;

    }

    public void setId(int id) {

        this.id = id;

    }

    public String getName() {

        return name;

    }

    public void setName(String name) {

        this.name = name;

    }

    public String getAddress() {

        return address;

    }

    public void setAddress(String address) {

        this.address = address;

    }

    @Override

    public String toString() {

        return "Animal{" +

                "id=" + id +

                ", name='" + name + '\'' +

                ", address='" + address + '\'' +

                '}';

    }
}

Application Output

Let’s know how we will run our application
You can create an executable JAR file, and run the spring boot application by using the below Maven or Gradle commands as shown −

mvn clean install

After you get “BUILD SUCCESS”, you can find the JAR file under the target directory.

gradle clean build

After you get “BUILD SUCCESSFUL”, you can find the JAR file under the build/libs directory.

You can run the JAR file by using the command shown below −

java –jar

This will start the application on the Tomcat port 8089 as shown below −

Postman Collections

Now hit the URL shown below in the POSTMAN application and see the output.

POST API URL is: http://localhost:8089/animal/add

Now hit the URL shown below in the POSTMAN application and see the output.

GET API URL is: http://localhost:8080/animal/animalByName

Here I have attached the GitHub file which you will find here

Reference:

https://www.tutorialspoint.com/spring_boot_h2/index.htm
https://www.javaguides.net/2019/07/spring-boot-save-findbyid-findall.html

Original article source at: https://blog.knoldus.com/

#spring #webflux 

Getting Started with Spring Web-flux

How to Use Java Records With Spring WebFlux and Spring Data

Traditionally, Java developers have depended on constructors, accessors, equals, hashCode, and toString to define classes for basic aggregation of values. Let's look at the characteristics and benefits of Java records and how to use them to develop a REST API and query a database.

  1. The record Keyword
  2. Java Record Restrictions and Rules
  3. Use Java Records With Spring WebFlux and Spring Data
  4. Java Records Advantages and Limitations

#java #webflux #spring 

How to Use Java Records With Spring WebFlux and Spring Data
Coding  Fan

Coding Fan

1633318278

Create Swagger documentation for Spring WebFlux Functional Programming

In this tutorial we will understand How to generate swagger documents for spring WebFlux functional style programming models using OpenAPI 3 .

GitHub:
https://github.com/Java-Techie-jt/routerfunction-openapi 

#spring #webflux #java 

Create Swagger documentation for Spring WebFlux Functional Programming
Dylan  Iqbal

Dylan Iqbal

1629778075

Java Microservices with Spring Boot, Spring WebFlux and JHipster

This video shows how to create a reactive microservices architecture using Spring Boot, Spring WebFlux, and JHipster.

#java #microservices #springboot #spring #webflux #jhipster

Java Microservices with Spring Boot, Spring WebFlux and JHipster
Sigrid  Farrell

Sigrid Farrell

1622645760

WebFlux: Reactive Programming With Spring, Part 3

This is the third part of my blog series on reactive programming, which will give an introduction to WebFlux — Spring’s reactive web framework.

1. An Introduction to Spring Webflux

The original web framework for Spring — Spring Web MVC — was built for the Servlet API and Servlet containers.

WebFlux was introduced as part of Spring Framework 5.0. Unlike Spring MVC, it does not require the Servlet API. It is fully asynchronous and non-blocking, implementing the Reactive Streams specification through the Reactor project (see my previous blog post).

WebFlux requires Reactor as a core dependency but it is also interoperable with other reactive libraries via Reactive Streams.

#java #tutorial #spring #reactive programming #reactor #webflux

WebFlux: Reactive Programming With Spring, Part 3

SpringBoot WebFlux Functional RestAPIs » grokonez

https://grokonez.com/spring-framework/spring-webflux/springboot-webflux-functional-restapis

SpringBoot WebFlux Functional RestAPIs

Reactive programming is about non-blocking applications. And Spring Framework 5 includes a new spring-webflux module, supports Reactive Streams for communicating backpressure across async components and libraries. So in the tutorial, JavaSampleApproach will guide you through the steps for creating a SpringBoot WebFlux Functional restful APIs.

Related posts:

I. Technologies

– Java: 1.8 – Maven: 3.3.9 – Spring Tool Suite: Version 3.9.0.RELEASE – Spring Boot: 2.0.0.M4 – Spring Boot Starter Webflux

II. Spring WebFlux Functional

Spring Framework 5.0 supports WebFlux with fully asynchronous and non-blocking and does NOT require the Servlet API(Unlike Spring MVC).

Spring WebFlux supports 2 distinct programming models:
– Annotation-based with @Controller
– Functional with Java 8 lambda style

In the tutorial, we will introduce WebFlux with Functional.
For starting with WebFlux, SpringBoot supports a collection dependency: spring-boot-starter-webflux.

With Spring WebFlux Functional, we use {HandlerFunctions, RouterFunctions} to develop.

1. HandlerFunctions

HandlerFunctions will handle incoming HTTP requests through ServerRequest, and return a Mono

@Component
public class CustomerHandler {
	
	...
	
    public Mono getAll(ServerRequest request) {
		...
		return ServerResponse.ok().contentType(MediaType.APPLICATION_JSON).body(customers, Customer.class);
    }
    
    ...
    
    public Mono putCustomer(ServerRequest request) {
		...
		return responseMono
                .flatMap(cust -> ServerResponse.ok().contentType(MediaType.APPLICATION_JSON).body(fromObject(cust)));
    }

    ...
	
    public Mono deleteCustomer(ServerRequest request) {
		...
		return responseMono
                .flatMap(strMono -> ServerResponse.ok().contentType(MediaType.TEXT_PLAIN).body(fromObject(strMono)));
    }
}

2. RouterFunction

RouterFunction handle all incoming requests. It takes a ServerRequest, and returns a Mono. If a request matches a particular route, a handler function is returned; otherwise it returns an empty Mono.

More at:

https://grokonez.com/spring-framework/spring-webflux/springboot-webflux-functional-restapis

SpringBoot WebFlux Functional RestAPIs

#springboot #webflux #restapi #functional

SpringBoot WebFlux Functional RestAPIs » grokonez

SpringBoot WebFlux Annotation-based RestAPIs » grokonez

https://grokonez.com/spring-framework/spring-webflux/springboot-webflux-annotation-based-programming-model

SpringBoot WebFlux Annotation-based RestAPIs

Reactive programming is about non-blocking applications. And Spring Framework 5 includes a new spring-webflux module, supports Reactive Streams for communicating backpressure across async components and libraries. So in the tutorial, JavaSampleApproach will guide you through the steps for creating a SpringBoot WebFlux Annotation-based restful APIs.

Related posts:

I. Technologies

– Java: 1.8 – Maven: 3.3.9 – Spring Tool Suite: Version 3.9.0.RELEASE – Spring Boot: 2.0.0.M4 - Spring Boot Starter Webflux

II. Spring WebFlux

Spring Framework 5.0 supports WebFlux with fully asynchronous and non-blocking and does NOT require the Servlet API(Unlike Spring MVC).

Spring WebFlux supports 2 distinct programming models:

  • Annotation-based with @Controller
  • Functional with Java 8 lambda style

In the tutorial, we will introduce WebFlux with Annotation-based.
For starting with WebFlux, SpringBoot supports a collection dependency: spring-boot-starter-webflux.

Sample code:


@RestController
@RequestMapping(value="/api/customer")
public class RestControllerAPIs {
	
    @GetMapping("/")
    public Flux getAll() {
	
    	...
    }
    
	@GetMapping("/{id}")
    public Mono getCustomer(@PathVariable Long id) {
		
		...
    }
}
  • reactor.core.publisher.Flux: is a standard Publisher representing a reactive sequence of 0…N items, optionally terminated by either a success signal or an error.
  • reactor.core.publisher.Mono: Mono is a specialized Publisher that emits at most single-valued-or-empty result.

III. Practice

In the tutorial, We create a SpringBoot project as below: springboot webflux annotation-based - project structure

Step to do:

  • Create SpringBoot project
  • Create data model
  • Implement Spring WebFlux APIs
  • Run and check results

1. Create SpringBoot project

Using SpringToolSuite, create a SpringBoot project with Reactive Web dependency: springboot webflux reactive - select reactive web

Check pom.xml after creating:

More at:

https://grokonez.com/spring-framework/spring-webflux/springboot-webflux-annotation-based-programming-model

SpringBoot WebFlux Annotation-based RestAPIs

#springboot #webflux #annotation #restapi

SpringBoot WebFlux Annotation-based RestAPIs » grokonez
Brooke  Giles

Brooke Giles

1617681360

Backpressure Mechanism in Spring WebFlux

Spring WebFlux provides Reactive Programming to web applications. The asynchronous and non-blocking nature of Reactive design improves performance and memory usage. Project Reactor provides those capabilities to efficiently manage data streams.

However, backpressure is a common problem in these kinds of applications. In this tutorial, we’ll explain what it is and how to apply backpressure mechanism in Spring WebFlux to mitigate it.

#webflux #spring-boot

Backpressure Mechanism in Spring WebFlux
Ansley  Krajcik

Ansley Krajcik

1616143440

Spring WebFlux, Kotlin Coroutines, and RSocket

This is an overview of the new tutorial about Spring Boot with Kotlin and RSocket. It starts from basics, guiding you step by step to more advanced scenarios.

  • 0:00 Introduction
  • 00:22 Spring guides page
  • 00:41 The new tutorial
  • 01:00 Downloading the sources
  • 01:27 Repository branches
  • 01:41 Browsing the sources
  • 01:54 Gradle dependencies
  • 02:31 HtmlController
  • 02:57 MessageResource
  • 03:06 FakeMessageService
  • 03:30 Running the application
  • 03:59 More about the tutorial
  • 04:36 Compare with branch
  • 05:52 The challenge

https://spring.io/guides/tutorials/spring-webflux-kotlin-rsocket/

Anton Arhipov https://twitter.com/antonarhipov

Kotlin is an excellent choice for server-side app development.
To learn more visit https://kotlinlang.org/lp/server-side

Follow Kotlin on Twitter https://twitter.com/kotlin

#kotlin #webflux #spring-boot

Spring WebFlux, Kotlin Coroutines, and RSocket

Spring WebFlux Tutorial: How to Build a Reactive Web App

Spring WebFlux is key to creating reactive, high data flow systems. Today, we’ll help you get started with your first WebFlux application.

Reactive systems allow for the unparalleled responsiveness and scalability that we need in our high data flow world. However, reactive systems need tools and developers specially trained to implement these unique program architectures. Spring WebFlux with Project Reactor is a framework specially built to meet the reactive needs of modern companies.

Today, we’ll help you get started with WebFlux by explaining how it fits with other reactive stack tools, how it’s different, and how to make your first app.

Here’s what we’ll cover today:

  • What is a Reactive System?
  • What is Project Reactor?
  • What is Spring WebFlux?
  • Salient Features of Spring WebFlux
  • Get Started with Spring WebFlux
  • Next steps for your learning

What is a Reactive System?

Reactive Systems are systems designed with a reactive architectural pattern that prioritizes the use of loosely coupled, flexible, and scalable components. They’re also designed with failure resolution in mind to ensure most of the system will still operate even if one fails.

#programming #java #software-development #webflux #spring-boot

Spring WebFlux Tutorial: How to Build a Reactive Web App
Seamus  Quitzon

Seamus Quitzon

1602851974

Project Reactor — Reactive Programming With Spring, Part 2

This is the second part of my blog series on reactive programming, providing an overview of Project Reactor, a reactive library based on the Reactive Streams specification. Part 1 covered an introduction to reactive programming.

1. An Introduction to Project Reactor

Reactive programming is supported by Spring Framework since version 5. That support is built on top of Project Reactor.

Project Reactor (or just Reactor) is a Reactive library for building non-blocking applications on the JVM and is based on the Reactive Streams Specification. The reactor is the foundation of the reactive stack in the Spring ecosystem and it is being developed in close collaboration with Spring. WebFlux, Spring’s reactive-stack web framework, requires Reactor as a core dependency.

1.1 Reactor Modules

Project Reactor consists of a set of modules as listed in the Reactor documentation. The modules are embeddable and interoperable. The main artifact is Reactor Core which holds the reactive types Flux and Mono, that implement the Reactive Stream’s Publisher interface (for details see the first blog post of this series) and a set of operators that can be applied on these.

Some other modules are:

  • Reactor Test — which provides some utilities for testing reactive streams
  • Reactor Extra — that provides some additional Flux operators
  • Reactor Netty — non-blocking and backpressure-ready TCP, HTTP, and UDP clients and servers — based on the Netty framework
  • Reactor Adapter — for adapting to/from other reactive libraries such as RxJava2 and Akka Streams
  • Reactor Kafka — a reactive API for Kafka which enables messages to be published to and consumed from Kafka

1.2 Set up a Project

Before we continue, if you want to set up a project and run some of the code samples below, generate a new Spring Boot application using Spring Initializr. As dependency select Spring Reactive Web. After importing the project in your IDE have a look at the POM file and you will see that the spring-boot-starter-webflux dependency is added which will also bring in the reactor-core dependency. Also, the reactor-test has been added as a dependency. Now you are ready to run the coming code examples.

XML

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-webflux</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>io.projectreactor</groupId>
            <artifactId>reactor-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

#java #tutorial #reactive programming #reactor #webflux

Project Reactor — Reactive Programming With Spring, Part 2
Shawn  Durgan

Shawn Durgan

1602551377

Creating a Reactive Restful API with Spring Boot

Overview

In this article I want to show how easily it is to create a reactive REST API with Spring Boot. I would like to take a simple Use Case and use this example to show how quick it is possible to create an “active” non-blocking REST API with Spring Boot.

In the last months and weeks I was working on two different modern mobile apps/ web apps. Quite quickly I realized that it can be very inconvenient if you have to ask an API from the client side all the time if there are changes. As you surely know you can do this by polling. But I don’t think this is very elegant. It also causes a lot of unnecessary traffic.

A technically more elegant solution would be if the consumer of the API could subscribe to an endpoint, and this endpoint would inform the client about changes.

I would like to use so-called Server-Sent Events (short: SSE) for this. Server-Sent-Events is a HTTP-Standard. It allows an application to process a unidirectional event stream and receive updates whenever the server sends data. At this point I would like to briefly explain why I chose SSE and not WebSockets. WebSockets provide bidirectional communication between client and server, SSE provides unidirectional communication. However, WebSockets are not a HTTP protocol and do not offer standards for error handling unlike SSE.

Scenario

In my current own project, which deals with the implementation of a platform for trainers and workouts, I have implemented a microservice that takes care of training courses. From this service I take one scenario as an example. The scenario to be considered is quite simple and clear.

The idea is that User A can create a new course and User B will get updated the list of available courses without reloading the page. The client component should not have to constantly poll the service.

For this we need to provide the following endpoints: one endpoint where the client can create a new course (POST), an endpoint that allows the client to retrieve all existing courses (GET). And of course, the most interesting: the already discussed SSE endpoint that allows consumers to stream events.

HTTP GET /course

HTTP GET /course/sse

HTTP POST /course

It is also important to me that we can realize this scenario with any database. In another service I had used a MongoDB that already provides a Reactive Stream implementation with the ReactiveMongoRepository. This means that the repository already returns Mono or Flux instead of T or List. I will report on my experiences using the ReactiveMongoRepository in another article.

#webflux #reactive #spring-boot #microservices #java

Creating a Reactive Restful API with Spring Boot
Zena  Sporer

Zena Sporer

1598349101

Spring MVC Async vs Spring WebFlux

undefined

#reactive #spring mvc #webflux

Spring MVC Async vs Spring WebFlux