Reader small image

You're reading from  Modern API Development with Spring 6 and Spring Boot 3 - Second Edition

Product typeBook
Published inSep 2023
Reading LevelIntermediate
PublisherPackt
ISBN-139781804613276
Edition2nd Edition
Languages
Concepts
Right arrow
Author (1)
Sourabh Sharma
Sourabh Sharma
author image
Sourabh Sharma

Sourabh Sharma is a Senior Development Manager at Oracle with over 20 years of experience in the industry. He is a manager and architect who has been designing on-premise and cloud-based applications using Java, Javascript, and Oracle DB. Sourabh has worked with leading companies and delivered enterprise products and applications. His expertise lies in conceptualizing, modeling, designing, and developing N-tier and cloud-based web applications while leading teams. Sourabh's experience also includes developing microservice-based solutions and implementing various types of workflow and orchestration engines. He believes in continuous learning and sharing knowledge through his books and training.
Read more about Sourabh Sharma

Right arrow

Asynchronous API Design

So far, we have developed RESTful web services based on the imperative model, where calls are synchronous. What if you want to make code async and non-blocking? This is what we are going to do in this chapter. You’ll learn about asynchronous API design in this chapter, where calls are asynchronous and non-blocking. We’ll develop these APIs using Spring WebFlux, which is based on Project Reactor (https://projectreactor.io). Reactor is a library for building non-blocking apps on a Java virtual machine (JVM).

First, we’ll walk through the reactive programming fundamentals, and then we’ll migrate the existing e-commerce REST API (which we learned about in Chapter 4, Writing Business Logic for APIs) to an asynchronous (reactive) API to make things easier by comparing the existing (imperative) way and reactive way of programming. The code will make use of R2DBC for database persistence, which supports reactive programming.

We’...

Understanding Reactive Streams

Normal Java code achieves asynchronicity by using thread pools. Your web server uses a thread pool to serve requests – it assigns a thread to each incoming request. The application uses the thread pool for database connections too. Each database call uses a separate thread and waits for the result. Therefore, each web request and database call uses its own thread. However, there is a wait associated with this and, therefore, these are blocking calls. The thread waits and utilizes the resources until a response is received back from the database or a response object is written. This is kind of a limitation when you scale as you can only use the resources available to the JVM. You overcome this limitation by using a load balancer with other instances of the service, which is a type of horizontal scaling.

In the last decade, there has been a rise in client-server architecture. Lots of IoT-enabled devices, smartphones that have native apps, first...

Exploring Spring WebFlux

Existing Servlet APIs are blocking APIs. They use input and output streams, which block APIs. Servlet 3.0 containers evolve and use the underlying event loop. Async requests are processed asynchronously but read and write operations still use blocking input/output streams. The Servlet 3.1 container has evolved further, supporting asynchronicity and having the non-blocking I/O stream APIs. However, there are certain Servlet APIs, such as request.getParameters(), which parse the blocking request body and provide synchronous contracts such as Filter. The Spring MVC framework is based on the Servlet API and Servlet containers.

Therefore, Spring provides Spring WebFlux, which is fully non-blocking and provides backpressure functionality. It provides concurrency with a small number of threads and scales with fewer hardware resources. WebFlux provides fluent, functional, and continuation-style APIs to support the declarative composition of asynchronous logic. Writing...

Understanding DispatcherHandler

DispatcherHandler, a front controller in Spring WebFlux, is the equivalent of DispatcherServlet in the Spring MVC framework. DispatcherHandler contains an algorithm that makes use of special components – HandlerMapping (maps requests to the handler), HandlerAdapter (a DispatcherHandler helper to invoke a handler mapped to a request), and HandlerResultHandler (a palindrome of words, for processing the result and forming results) – for processing requests. The DispatcherHandler component is identified by a bean named webHandler.

It processes requests in the following way:

  1. A web request is received by DispatcherHandler.
  2. DispatcherHandler uses HandlerMapping to find a matching handler for the request and uses the first match.
  3. It then uses the respective HandlerAdapter to process the request, which exposes HandlerResult (the value returned by HandlerAdapter after processing). The return value could be one of the following...

Implementing reactive APIs for our e-commerce app

Now that you have an idea of how Reactive Streams works, we can go ahead and implement REST APIs that are asynchronous and non-blocking.

You’ll recall that we are following the design-first approach, so we need the API design specification first. However, we can reuse the e-commerce API specification we created previously in Chapter 3, API Specifications and Implementation.

OpenAPI Codegen is used to generate the API interface/contract that creates the Spring MVC-compliant API Java interfaces. Let’s see what changes we need to do to generate the reactive API interfaces.

Changing OpenAPI Codegen for reactive APIs

You need to tweak a few OpenAPI Codegen configurations to generate Spring WebFlux-compliant Java interfaces, as shown next:

{  "library": "spring-boot",
  "dateLibrary": "java8",
  "hideGenerationTimestamp": true,
 ...

Summary

I hope you enjoyed learning about reactive API development with an asynchronous, non-blocking, and functional paradigm. At first glance, you may find it complicated if you are not very familiar with the fluent and functional paradigm, but with practice, you’ll start writing only functional-style code. Definitely, familiarity with Java streams and functions will help you to grasp the concepts easily.

Now that you have reached the end of this chapter, you have the skills to write functional and reactive code. You can write reactive, asynchronous, and non-blocking code and REST APIs. You also learned about R2DBC, which will become more solid and enhanced in the future as long as reactive programming continues to be used.

In the next chapter, we’ll explore the security aspect of RESTful service development.

Questions

  1. Do you really need the reactive paradigm for application development?
  2. Are there any disadvantages to using the reactive paradigm?
  3. Who plays the role of the subscriber in the case of an HTTP request in Spring WebFlux?

Answers

  1. Yes, it is required only if you need vertical scaling. In the cloud, you pay to use the resources, and reactive applications help you to use resources optimally. This is a new way of achieving scale. You need a small number of threads compared to non-reactive applications. The cost of connection to a database, I/O, or any external source is a callback; therefore, reactive-based applications do not require much memory. However, while reactive programming is superior in terms of vertical scaling, you should continue using your existing or non-reactive applications. Even Spring recommends that. There is no new or old style; both can co-exist. However, when you need scaling for any special component or application, you can go the reactive way. A few years back, Netflix replaced the Zuul API gateway with the reactive Zuul2 API gateway. This helped them to achieve scale. However, they still have/use non-reactive applications.
  2. There are pros and cons to everything. Reactive...
lock icon
The rest of the chapter is locked
You have been reading a chapter from
Modern API Development with Spring 6 and Spring Boot 3 - Second Edition
Published in: Sep 2023Publisher: PacktISBN-13: 9781804613276
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €14.99/month. Cancel anytime

Author (1)

author image
Sourabh Sharma

Sourabh Sharma is a Senior Development Manager at Oracle with over 20 years of experience in the industry. He is a manager and architect who has been designing on-premise and cloud-based applications using Java, Javascript, and Oracle DB. Sourabh has worked with leading companies and delivered enterprise products and applications. His expertise lies in conceptualizing, modeling, designing, and developing N-tier and cloud-based web applications while leading teams. Sourabh's experience also includes developing microservice-based solutions and implementing various types of workflow and orchestration engines. He believes in continuous learning and sharing knowledge through his books and training.
Read more about Sourabh Sharma