- Spring 5.0 Microservices(Second Edition)
- Rajesh R V
- 851字
- 2021-07-02 19:45:03
Reactive microservices using Spring WebFlux
Reactive programming in Java is based on the Reactive Streams specification. Reactive stream specification defines the semantics for asynchronous stream processing or flow of events between disparate components in a non-blocking style.
Unlike the standard observer pattern, Reactive Streams allow to maintain sequence, notification on completion, and notification when there is an error with full backpressure support. With backpressure support, a receiver can set terms such as how much data it wants from the publisher. Also, the receiver can start receiving data only when data is ready to be processed. Reactive Streams are particularly useful for handling different thread pools for different components, or in the case of integrating slow and fast components.
Spring Framework 5 integrates reactive programming principles at its core as WebFlux. Spring 5 WebFlux is based on Reactive Streams specification. Under the hood, Spring's Web Reactive Framework uses the Reactor project (https://projectreactor.io) for implementing reactive programming. Reactor is an implementation of Reactive Streams specification. With Spring Framework, developers can also choose to use RxJava instead of Reactor.
In this section, we will see how to build Reactive Spring Boot microservices using Spring 5 WebFlux libraries. These libraries help developers to create asynchronous, non-blocking HTTP servers with full backpressure support, without coding callback methods. Note that it is not a one-size-fits solution in all cases and, if not used property, this can backfire on the quality of services. Also, developers need to be sure that the downstream components support full reactive programming.
In order to get full power of reactive programming, reactive constructs should be used end-to-end from client, endpoint, and to the repository. That means, if a slow client accesses a reactive server, then the data read operations in the repository can slow down to match the slowness of the client.
Spring WebFlux supports two options for implementing Spring Boot applications. The first approach is annotation based with @Controller and the other annotations generally used with Spring Boot. The second approach is functional programming Java 8 lambda style coding.
Let us build a sample using the annotation style reactive programming using WebFlux.
Follow these steps to build a reactive Spring Boot application:
- Go to https://start.spring.io, and generate a new Spring Boot project.
- Select Reactive Web under the Web section:

- Generate project, and import the newly generated project into STS.
- Examine pom.xml; there is only one difference. Instead of spring-boot-starter-web, this project uses spring-boot-starter-webflux in the dependency section. Following is the dependency to Spring Webflux:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
- Add the GreetingController and Greet classes from chapter3.bootrest to the Application.java class.
- Run this project, and test with a browser by pointing to http://localhost:8080. You will see the same response.
- Let us add some Reactive APIs to enable reactive programming to the Boot application. Let us modify RestController. Let us add a construct, Mono, as follows:
@RequestMapping("/")
Mono<Greet> greet(){
return Mono.just(new Greet("Hello World!"));
}
In this case, the response body uses Mono, which means that the Greet object will be serialized only when Mono is completed in an asynchronous non-blocking mode. Since we have used Mono, this method just creates a single definitive item.
In this case, Mono is used to declare a logic which will get executed as soon as the object is deserialized. You may consider Mono as a placeholder (deferred) for zero or one object with a set of callback methods.
In case of Mono as a parameter to a controller method, the method may be executed even before the serialization gets over. The code in the controller will decide what we want to do with the Mono object. Alternately, we can use Flux. Both these constructs will be explained in detail in the next section.
Let us now change the client. Spring 5 reactive introduced WebClient and WebTestClient as an alternate to RestTemplate. WebClient is fully support reactive under the hood.
The client-side code is as follows:
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.DEFINED_PORT)
public class ApplicationTests {
WebTestClient webClient;
@Before
public void setup() {
webClient = WebTestClient.bindToServer()
.baseUrl("http://localhost:8080").build();
}
@Test
public void testWebFluxEndpoint() throws Exception {
webClient.get().uri("/")
.accept(MediaType.APPLICATION_JSON)
.exchange()
.expectStatus().isOk()
.expectBody(Greet.class).returnResult()
.getResponseBody().getMessage().equals("Hello World!");
}
WebTestClient is a purpose build class for testing WebFlux server. WebClient, another client class similar to RestTemplate is more handy when invoking WebFlux from a non-testing client. The preceding test code first creates a WebTestClient with the server URL. Then it executes a get method on the / URL, and verifies it against the existing result.
- Run the test from the command prompt using mvn install. You will not notice any difference in functionality, but the execution model has changed under the hood.
- Apache ZooKeeper Essentials
- 零基礎學Scratch少兒編程:小學課本中的Scratch創意編程
- 無代碼編程:用云表搭建企業數字化管理平臺
- Java加密與解密的藝術(第2版)
- C#程序設計教程
- Instant Typeahead.js
- Vue.js 3.0源碼解析(微課視頻版)
- Building Cross-Platform Desktop Applications with Electron
- 軟件測試技術指南
- Java實戰(第2版)
- UNIX Linux程序設計教程
- Mastering Akka
- scikit-learn Cookbook(Second Edition)
- Kotlin進階實戰
- Python面試通關寶典