Statistics
35
Views
0
Downloads
0
Donations
Support
Share
Uploader

高宏飞

Shared on 2026-01-16

AuthorVincenzo Racca

DESCRIPTION This book is a complete guide to designing and implementing scalable, secure, and modern APIs in a microservices architecture. Covering both synchronous communication via REST, GraphQL, and gRPC, as well as asynchronous communication with Kafka, it equips you with the tools to build efficient, reliable, and observable APIs. Learn best practices for designing REST APIs, including HTTP verb usage and the API-first approach. Explore Spring Boot technologies like WebFlux and virtual threads to build scalable REST APIs. The book also demonstrates how to use Spring Cloud Stream for broker-agnostic asynchronous communication to build robust event-driven architectures. To ensure observability, you will implement logging, monitoring, and tracing with Grafana, Prometheus, and Tempo. Security is key, and the book covers OAuth2 and OpenID Connect using Spring Security and Keycloak for centralized authentication. Finally, discover how to deploy microservices with Docker and Kubernetes, mastering containerization and orchestration. KEY FEATURES ● Design scalable and observable APIs for cloud-native microservices. ● Master REST, GraphQL, gRPC, and event-driven API best practices. ● Secure APIs with OAuth2, OpenID Connect, and Spring Security. WHAT YOU WILL LEARN ● Design scalable, secure REST APIs with Spring Boot, WebFlux, and virtual threads. ● Implement GraphQL and gRPC for modern APIs. ● Master asynchronous communication with Kafka and Spring Cloud Stream. ● Achieve observability with logging, metrics, and distributed tracing. ● Deploy microservices on Docker and Kubernetes with ease. WHO THIS BOOK IS FOR This book is for software developers and architects aiming to design scalable, secure, and modern APIs in a microservices architecture. Prior knowledge of Java and Spring Framework is recommended. TABLE OF CONTENTS 1. Introduction to REST Architecture and API-first Approach 2. Reactive REST APIs with Spring WebFlux 3. Easily Scalable APIs with Virtual Threads 4. G

Tags
No tags
ISBN: 9365898080
Publisher: BPB Publications
Publish Year: 2025
Language: 英文
Pages: 289
File Format: PDF
File Size: 18.9 MB
Support Statistics
¥.00 · 0times
Text Preview (First 20 pages)
Registered users can read the full content for free

Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.

 i Spring Boot 3 API Mastery Write scalable, reactive, and secure APIs for microservices with Spring Boot 3 and Java 21 Vincenzo Racca www.bpbonline.com
ii  First Edition 2025 Copyright © BPB Publications, India ISBN: 978-93-65898-088 All Rights Reserved. No part of this publication may be reproduced, distributed or transmitted in any form or by any means or stored in a database or retrieval system, without the prior written permission of the publisher with the exception to the program listings which may be entered, stored and executed in a computer system, but they can not be reproduced by the means of publication, photocopy, recording, or by any electronic and mechanical means. LIMITS OF LIABILITY AND DISCLAIMER OF WARRANTY The information contained in this book is true to correct and the best of author’s and publisher’s knowledge. The author has made every effort to ensure the accuracy of these publications, but publisher cannot be held responsible for any loss or damage arising from any information in this book. All trademarks referred to in the book are acknowledged as properties of their respective owners but BPB Publications cannot guarantee the accuracy of this information. www.bpbonline.com
 iii Dedicated to My parents Pino and Nunzia Racca, whose love, support, and guidance have shaped who I am today
iv  About the Author Vincenzo Racca is a Software Engineer specializing in Java, Spring, and Cloud technologies. He has enhanced his technical expertise by earning certifications in the Spring Framework, Kubernetes, and AWS. Vincenzo shares his knowledge by publishing articles on Java, Spring, and Cloud-native development.
 v About the Reviewers v Lucas Fernandes is passionate about software engineering, specializing in the development of highly scalable, resilient, and fault-tolerant applications. He has extensive expertise in all phases of the software development lifecycle, from conception to deployment. A strong advocate for microservices and event-driven architectures, Lucas has significant experience with technologies such as Java, Kotlin, the Spring ecosystem, Kafka, Kubernetes, and AWS services. As a cloud computing specialist, he has deep expertise in public cloud platforms, particularly AWS, where he holds two certifications. Currently, he works at Iteris Consulting and Software as a Tech Lead and Solutions Architect, designing and developing critical applications, especially in the financial sector. Recently, he also embarked on a new journey as a writer on Medium, where he shares his knowledge and experiences in the tech industry, promotes best practices, and inspires the developer community. v Modassir Kashani is a skilled Software Engineer with extensive expertise in the Fintech domain. He has a wealth of experience in API development, microservices architecture, cloud deployment, and site reliability engineering. Modassir specializes in designing and developing payment applications, with a focus on crafting innovative solutions to real-world challenges using payment APIs. Currently, he is pursuing a Master’s degree in Artificial Intelligence at Queen Mary University of London.
vi  Acknowledgement I would like to thank everyone who encouraged me to write this book. A special thanks to my girlfriend, Anna, my sister, Sonia, and my friend, Chiara, for their unwavering support. I am deeply grateful to BPB Publications for believing in me and giving me the opportunity to write a book that holds such personal significance. Thank you to their entire team for helping me refine and enhance the content of this work. I also extend my gratitude to my colleagues, both past and present, who have contributed to my growth and development by generously sharing their knowledge and experiences with me. Finally, my heartfelt thanks go to all the readers of this book for placing their trust in me. Your support is my greatest motivation to continue sharing knowledge and learning together.
 vii Preface In an ever-evolving technological landscape, the ability to design and implement scalable, secure, and efficient APIs has become a cornerstone of modern software development. APIs are not merely tools for communication between systems—they form the backbone of microservices architectures, enabling businesses to innovate and adapt to change swiftly. This book was born out of the realization that many developers face challenges in creating APIs that not only meet immediate requirements but are also robust, future-proof, and aligned with industry best practices. It is designed to provide readers with a comprehensive guide to mastering API design and implementation using Spring Boot, one of the most powerful and versatile frameworks available today. Throughout these chapters, we will explore how to build APIs using Spring Boot, covering synchronous APIs such as REST, GraphQL, and gRPC, as well as asynchronous, event- driven APIs powered by Apache Kafka and Spring Cloud Stream. We will delve into topics like observability, distributed tracing, and security using OAuth2 and OpenID Connect. Finally, we will deploy microservices on Docker and Kubernetes, completing the journey from design to production. This book is intended for developers and architects seeking to enhance their understanding of API design using Spring Boot in the context of cloud-native applications. It is a practical guide filled with real-world examples to help you not just learn but apply these concepts to your projects. I hope this book serves as a valuable resource in your journey as a developer. Thank you for embarking on this learning experience with me. Chapter 1: Introduction to REST Architecture and API-first Approach - This chapter covers a journey into microservice development. It navigates the intricacies of synchronous vs. asynchronous communication, elucidates the foundational principles of REST architecture, and delves into the nuances of managing API versioning. The chapter culminates with an exploration of the API-first approach, illuminating its significance in crafting scalable and well-designed microservices. Through a blend of theoretical insights and practical considerations, the reader gains a solid foundation for embarking on the subsequent chapters, setting the stage for a comprehensive exploration of API development in the evolving landscape of microservices architecture.
viii  Chapter 2: Reactive REST APIs with Spring WebFlux - This chapter covers the reactive programming paradigm and explains how it differs from traditional approaches. It introduces Spring WebFlux, a powerful framework for building high-performance, non- blocking APIs. You will explore concepts like reactive streams and event loops while creating scalable REST APIs. Practical examples illustrate how reactive programming enhances responsiveness, making applications more efficient in handling concurrent requests. Chapter 3: Easily Scalable APIs with Virtual Threads - This chapter covers the power of Virtual Threads introduced in Java 21 for building highly scalable synchronous APIs. It explains how Virtual Threads revolutionizes concurrency management, making it possible to handle numerous requests efficiently without blocking. The reader will learn to integrate Virtual Threads with Spring MVC, analyze performance benefits, and explore real-world examples of creating scalable, production-ready APIs. Chapter 4: GraphQL with Spring Boot – This chapter covers the fundamentals of GraphQL, an alternative to REST for building flexible and client-focused APIs. It covers GraphQL schema, queries, and mutations, with practical examples using Spring Boot. You will understand how GraphQL enables efficient data fetching, reduces over-fetching and under-fetching, and supports evolving API requirements. By the end, the reader will be equipped to design and implement GraphQL APIs tailored to complex client needs. Chapter 5: Designing APIs with gRPC - This chapter covers gRPC, a high-performance, language-neutral framework for communication between microservices. It explores the use cases, benefits, and implementation of gRPC in a Spring Boot application. The reader will learn how Protocol Buffers work for defining services and messages, and compare gRPC with REST. Practical examples demonstrate how to create scalable, low-latency APIs, making it an essential tool for high-throughput distributed systems. Chapter 6: Asynchronous APIs with Spring Cloud Stream and Apache Kafka - This chapter covers building event-driven APIs for asynchronous communication between microservices. It explains how to use Apache Kafka as a message broker and Spring Cloud Stream for abstracting message processing. The reader will explore patterns like pub/sub and message partitioning. Through hands-on examples, the reader will understand how to implement APIs that handle asynchronous events efficiently. Chapter 7: Centralized Security with Spring Cloud Gateway - This chapter covers how to implement centralized authentication and authorization using Spring Cloud Gateway. It explores OAuth2 and OpenID Connect protocols, integrates Keycloak as an Identity Provider, and configures microservices as OAuth2 clients and resource servers.
 ix Chapter 8: Observability and Monitoring - This chapter covers observability and its importance in maintaining reliable APIs. It covers logging, metrics, and distributed tracing using tools like Grafana, Prometheus, and Tempo. The reader will learn to aggregate logs, monitor performance metrics, and trace request flows across microservices. By implementing observability best practices, the reader can quickly diagnose issues, optimize performance, and ensure a seamless user experience. Chapter 9: Deploying Applications on Kubernetes with Kind - This chapter covers the deployment of microservices using Docker and Kubernetes. It focuses on Kind, a lightweight tool for running Kubernetes clusters locally. The reader will explore concepts like Pods, Deployments, and Services, and understand how to manage scaling and networking. Hands-on examples guide the reader through deploying APIs, ensuring they are production-ready and aligned with cloud-native principles.
x  Code Bundle and Coloured Images Please follow the link to download the Code Bundle and the Coloured Images of the book: https://rebrand.ly/9db530 The code bundle for the book is also hosted on GitHub at https://github.com/bpbpublications/Spring-Boot-3-API-Mastery. In case there’s an update to the code, it will be updated on the existing GitHub repository. We have code bundles from our rich catalogue of books and videos available at https://github.com/bpbpublications. Check them out! Errata We take immense pride in our work at BPB Publications and follow best practices to ensure the accuracy of our content to provide with an indulging reading experience to our subscribers. Our readers are our mirrors, and we use their inputs to reflect and improve upon human errors, if any, that may have occurred during the publishing processes involved. To let us maintain the quality and help us reach out to any readers who might be having difficulties due to any unforeseen errors, please write to us at : errata@bpbonline.com Your support, suggestions and feedbacks are highly appreciated by the BPB Publications’ Family. Did you know that BPB offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.bpbonline. com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at : business@bpbonline.com for more details. At www.bpbonline.com, you can also read a collection of free technical articles, sign up for a range of free newsletters, and receive exclusive discounts and offers on BPB books and eBooks.
 xi Piracy If you come across any illegal copies of our works in any form on the internet, we would be grateful if you would provide us with the location address or website name. Please contact us at business@bpbonline.com with a link to the material. If you are interested in becoming an author If there is a topic that you have expertise in, and you are interested in either writing or contributing to a book, please visit www.bpbonline.com. We have worked with thousands of developers and tech professionals, just like you, to help them share their insights with the global tech community. You can make a general application, apply for a specific hot topic that we are recruiting an author for, or submit your own idea. Reviews Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions. We at BPB can understand what you think about our products, and our authors can see your feedback on their book. Thank you! For more information about BPB, please visit www.bpbonline.com. Join our book's Discord space Join the book's Discord Workspace for Latest updates, Offers, Tech happenings around the world, New Release and Sessions with the Authors: https://discord.bpbonline.com
xii  Table of Contents 1. Introduction to REST Architecture and API-first Approach ......................................... 1 Introduction ....................................................................................................................... 1 Structure ............................................................................................................................. 1 Objectives .......................................................................................................................... 2 Introduction to microservice architecture ..................................................................... 2 Synchronous Vs. asynchronous communication ......................................................... 3 Synchronous communication ....................................................................................... 4 Asynchronous communication ..................................................................................... 5 Fundamentals of REST architecture .............................................................................. 7 Restful API design ............................................................................................................ 8 Richardson Maturity Model level 0: The swamp of POX ........................................... 9 Richardson Maturity Model level 1: Resources ......................................................... 10 Richardson Maturity Model level 2: HTTP verbs ..................................................... 10 Richardson Maturity Model level 3: HTTP verbs ..................................................... 12 The concept of API idempotence ................................................................................ 12 API versioning strategies ........................................................................................... 14 Final considerations on REST API design ................................................................ 15 OpenAPI specification and tools .................................................................................. 16 API-first approach .......................................................................................................... 19 Conclusion ....................................................................................................................... 19 Points to remember ........................................................................................................ 19 2. Reactive REST APIs with Spring WebFlux ..................................................................... 21 Introduction ..................................................................................................................... 21 Structure ........................................................................................................................... 22 Objectives ........................................................................................................................ 22 Introduction to reactive paradigm ............................................................................... 22 Core concepts of the reactive framework ................................................................... 24 Event Loop vs. Thread-per-request ............................................................................. 30
 xiii REST APIs with Spring WebFlux ................................................................................. 31 Installation of Java 21................................................................................................. 32 Installation of Docker Desktop ................................................................................... 32 Installation of HTTPie ............................................................................................... 33 Set up the Spring WebFlux project ............................................................................ 33 Designing the product domain object ........................................................................ 35 Getting started with Spring WebFlux ....................................................................... 36 Exception handling in Spring WebFlux .................................................................... 54 Logging request and response in Spring WebFlux .................................................... 58 Functional endpoints in Spring WebFlux ................................................................. 60 Reactive REST client with Spring WebFlux ................................................................ 61 Testing reactive APIs ...................................................................................................... 63 Spring MVC vs. Spring WebFlux performance .......................................................... 66 Conclusion ....................................................................................................................... 69 Points to remember ........................................................................................................ 69 Exercises ........................................................................................................................... 69 3. Easily Scalable APIs with Virtual Threads ..................................................................... 71 Introduction ..................................................................................................................... 71 Structure ........................................................................................................................... 71 Objectives ........................................................................................................................ 72 Understanding virtual threads in Java ........................................................................ 72 Platform threads vs. virtual threads ........................................................................... 72 Virtual threads to simplify scalability in Java ............................................................ 73 Virtual threads in detail ............................................................................................. 73 Getting started with Spring MVC with virtual threads ............................................ 77 Introduction to Spring MVC ..................................................................................... 77 Spring MVC in practice ............................................................................................. 79 Paginated API in Spring MVC ................................................................................. 90 A new modern synchronous REST client: RestClient ............................................... 99 Testing in Spring MVC ................................................................................................ 104 Spring MVC performance comparison: Platform vs. virtual threads ................... 106 Choose between virtual threads and WebFlux ........................................................ 108
xiv  Conclusion ..................................................................................................................... 108 Points to remember ...................................................................................................... 109 Exercises ......................................................................................................................... 109 4. GraphQL with Spring Boot ...............................................................................................111 Introduction ....................................................................................................................111 Structure ......................................................................................................................... 112 Objectives ...................................................................................................................... 112 Fundamentals of GraphQL ......................................................................................... 112 Schemas and types .................................................................................................... 113 Queries and mutations ............................................................................................. 114 Implementing GraphQL APIs with Spring Boot ..................................................... 118 GraphQL N + 1 problem .......................................................................................... 128 Error handling in Spring for GraphQL ................................................................... 132 Optimizing GraphQL with document parsing caching ........................................... 134 GraphQL client in Spring ........................................................................................ 137 Testing GraphQL APIs ................................................................................................. 138 Comparing REST and GraphQL ................................................................................ 140 Conclusion ..................................................................................................................... 141 Points to remember ...................................................................................................... 142 Exercises ......................................................................................................................... 142 5. Designing APIs with gRPC .............................................................................................. 143 Introduction ................................................................................................................... 143 Structure ......................................................................................................................... 144 Objectives ...................................................................................................................... 144 Overview of gRPC ........................................................................................................ 144 The Protocol Buffers ................................................................................................. 145 Communication in gRPC ......................................................................................... 147 Comparison of gRPC and REST .............................................................................. 148 Integrating gRPC into Spring Boot applications ..................................................... 150 Implementation of the gRPC server ......................................................................... 151 Implementation of the gRPC client .......................................................................... 157
 xv Testing gRPC APIs........................................................................................................ 162 Conclusion ..................................................................................................................... 166 Points to remember ...................................................................................................... 167 Exercises ......................................................................................................................... 167 6. Asynchronous APIs with Spring Cloud Stream and Apache Kafka ....................... 169 Introduction ................................................................................................................... 169 Structure ......................................................................................................................... 170 Objectives ...................................................................................................................... 170 Asynchronous APIs ...................................................................................................... 171 HTTP polling ........................................................................................................... 171 Webhook.................................................................................................................... 172 HTTP Streaming ...................................................................................................... 173 WebSocket ................................................................................................................. 175 Publish/Subscribe ..................................................................................................... 176 Introduction to Apache Kafka .................................................................................... 177 Introduction to Spring for Apache Kafka ................................................................. 179 The Spring Cloud Stream project ...................................................................................... 181 An overview of Spring Cloud Function ................................................................... 182 Main concepts in Spring Cloud Stream ................................................................... 184 Message-driven microservices with Spring Cloud Stream .................................... 186 Getting started with Spring Cloud Stream .............................................................. 190 Implementing a producer with Spring Cloud Stream ............................................. 190 Implementing a consumer with Spring Cloud Stream ............................................ 196 Spring Cloud Stream at work .................................................................................. 201 The AsyncAPI specification .................................................................203 Error handling in Spring Cloud Stream .................................................................... 206 Testing Spring Cloud Stream applications ............................................................... 209 Conclusion ..................................................................................................................... 213 Points to remember ...................................................................................................... 214 Exercises ......................................................................................................................... 214
xvi  7. Centralized Security with Spring Cloud Gateway ...................................................... 215 Introduction ................................................................................................................... 215 Structure ......................................................................................................................... 216 Objectives ...................................................................................................................... 216 Introduction to OAuth2 and OpenID Connect ........................................................ 216 JSON Web Token ...................................................................................................... 217 OpenID Connect protocol ........................................................................................ 218 OAuth2 protocol....................................................................................................... 220 Using Keycloak as an identity server ........................................................................ 222 Running Keycloak locally ........................................................................................ 222 Configuring Keycloak ............................................................................................... 223 API Gateway with Spring Cloud Gateway .............................................................. 224 Getting started with Spring Cloud Gateway ........................................................... 226 Resilience with Spring Cloud Gateway ................................................................... 228 Implementing retry with retry filter ........................................................................ 228 Implementing circuit breaker with Resilience4J ...................................................... 229 OAuth2 client and resource servers with Spring Security ..................................... 233 Configuring the OAuth2 client on Keycloak ........................................................... 234 Configuring the OAuth2 client on Spring Security .......................................... 235 Spring Session with Redis to manage sessions .......................................... 241 Configuring the resource server on Spring Security ........................................ 242 Access token management in the OAuth2 client ....................................... 243 Resource server implementation .................................................................. 244 Role based access control with Spring Security ................................................ 246 Roles claim in the token ID ........................................................................... 246 Protecting APIs with RBAC in the resource server ................................... 248 Testing OIDC and OAuth2 flow with Spring Security .................................... 251 Configuring OAuth2Client for SPA .................................................................... 253 Conclusion ..................................................................................................................... 255 Points to remember ...................................................................................................... 256 Exercises ......................................................................................................................... 256
 xvii 8. Observability and Monitoring ........................................................................................ 257 Introduction ................................................................................................................... 257 Structure ......................................................................................................................... 258 Objectives ...................................................................................................................... 259 Log aggregation with Grafana Loki .......................................................................... 259 Logging in Spring Boot ............................................................................................ 259 Working with Loki .................................................................................................... 260 Metrics with Spring Boot Actuator and Prometheus .............................................. 262 Tracing with Micrometer, OpenTelemetry, and Grafana Tempo ........................... 267 Monitoring with Grafana ............................................................................................ 270 Conclusion ..................................................................................................................... 276 Points to remember ...................................................................................................... 276 Exercises ......................................................................................................................... 276 9. Deploying Applications on Kubernetes with Kind .................................................... 277 Introduction ................................................................................................................... 277 Structure ......................................................................................................................... 277 Objectives ...................................................................................................................... 278 Spring Boot with Docker ............................................................................................. 278 Introduction to container technology and Docker ................................................... 278 Containerizing a Spring Boot application ............................................................... 281 Running Spring Boot containers with Docker Compose ......................................... 284 Introduction to Kubernetes ......................................................................................... 287 Deployment and service in Kubernetes .................................................................... 289 Deploy your API locally with Kind ........................................................................... 292 Installation and creation of the cluster ..................................................................... 292 Deploy Easyshop to Kubernetes ............................................................................... 294 Writing deployment and service .............................................................................. 295 Running the cluster ................................................................................................. 302 Conclusion ..................................................................................................................... 305 Points to remember ...................................................................................................... 306 Exercises ......................................................................................................................... 306 Index
xviii 
Introduction to REST Architecture and API-first Approach  1 Chapter 1 Introduction to REST Architecture and API-first Approach Introduction In today's rapidly evolving landscape of software development, the advent of microservices architecture has revolutionized how applications are designed, built, and deployed. At the heart of this architectural paradigm lies the pivotal role of application programming interfaces (APIs), serving as the cornerstone for communication and interaction between microservices. In this chapter, we embark on a journey to explore the fundamental principles and practices that underpin the development of robust and scalable APIs within a microservices environment. Our exploration begins with a fundamental distinction between synchronous and asynchronous communication paradigms, illuminating the strengths and trade-offs of each approach in facilitating seamless interaction between microservices. We will delve into the Representational State Transfer (REST) architecture, unraveling its core principles of statelessness, uniform interface, and resource-based design. In addition, we will discuss the advantages of using the API-first approach with the OpenAPI specification. Structure In this chapter, we will discuss the following topics: • Introduction to microservice architecture • Synchronous Vs. asynchronous communication
2  Spring Boot 3 API Mastery • Fundamentals of REST architecture • Restful API design • OpenAPI specification and tools • API-first approach Objectives By the end of this chapter, you will have a clear understanding of synchronous and asynchronous communication between microservices, enabling you to evaluate and select the most appropriate method to use based on your use cases. You will appreciate REST architecture in detail, knowing best practices so that you can write clear APIs for your clients through the OpenAPI specification. Introduction to microservice architecture In recent years, microservices architecture has become increasingly popular in enterprise projects. In previous years, projects were mostly written with a monolithic architecture. In this architecture, the entire application is developed, tested, deployed, and scaled as a single unit. Figure 1.1 shows a typical monolithic architecture where an entire team works on the same source code. The following application shows the reads and writes from a single database: Figure 1.1: Example of monolithic architecture Microservice architecture divides an application into a set of independent and modular services which is responsible for a specific functionality. Each service in a microservice architecture can be developed, deployed, and scaled independently. Services communicate with each other through well-defined APIs and often use lightweight protocols such as HTTP or asynchronous messaging.