Hacking with Spring Boot 2.3: Reactive Edition
3/5
()
About this ebook
Spring Boot 2.3 is the hottest ticket in town...
...when it comes to Java development. Learn the latest features that can scale your apps including:
* Web and Data access
* Developer tools and test support
* Operational features
* Docker container baking
* Bottleneck discovery with BlockHound
* Messaging
* Security
* More!
Written cover-to-cover using Project Reactor, your apps will scale like never before.
Grab your copy today and learn to build top-notch, scalable solutions with modern tactics.
Greg L. Turnquist works on the Spring team at VMware. He is a committer to Spring Data, Spring Boot, R2DBC, Spring HATEOAS, and other Spring projects. He has written the Hacking with Spring Boot series as well as Packt's best-selling title, Learning Spring Boot 2.0 2nd Edition. He co-founded the Nashville Java User Group in 2010 and hasn't met a Java app (yet) that he doesn't like.
Be sure to check out his YouTube channel, Spring Boot Learning, where you learn about Spring Boot and have fun doing it at youtube/SpringBootLearning.
Related to Hacking with Spring Boot 2.3
Related ebooks
Hacking with Spring Boot 2.4: Classic Edition: Hacking with Spring Boot, #2 Rating: 0 out of 5 stars0 ratingsASP.NET Core 3 and React: Hands-On full stack web development using ASP.NET Core, React, and TypeScript 3 Rating: 0 out of 5 stars0 ratingsSpring Boot Cookbook Rating: 0 out of 5 stars0 ratingsBuilding Scalable Apps with Redis and Node.js Rating: 0 out of 5 stars0 ratingsSpring Boot and Single-Page Applications: Securing Your API with a Single-Page Application Frontend - Second Edition Rating: 0 out of 5 stars0 ratingsReact Components Rating: 0 out of 5 stars0 ratingsClojure for Java Developers Rating: 0 out of 5 stars0 ratingsReact.js Design Patterns: Learn how to build scalable React apps with ease (English Edition) Rating: 0 out of 5 stars0 ratingsYour First Week With Node.js Rating: 0 out of 5 stars0 ratingsWebSocket Essentials – Building Apps with HTML5 WebSockets Rating: 0 out of 5 stars0 ratingsIntelliJ IDEA Essentials Rating: 0 out of 5 stars0 ratingsJasmine JavaScript Testing - Second Edition Rating: 0 out of 5 stars0 ratingsBuilding a RESTful Web Service with Spring Rating: 5 out of 5 stars5/5Learning Angular for .NET Developers Rating: 0 out of 5 stars0 ratingsGo Programming Blueprints Rating: 0 out of 5 stars0 ratingsAngularJS Deployment Essentials Rating: 0 out of 5 stars0 ratingsGetting Started with React Rating: 0 out of 5 stars0 ratingsMastering Spring 5.0 Rating: 5 out of 5 stars5/5Monitoring Docker Rating: 0 out of 5 stars0 ratingsJava Hibernate Cookbook Rating: 0 out of 5 stars0 ratingsCORS Essentials Rating: 0 out of 5 stars0 ratingsMastering Gradle Rating: 0 out of 5 stars0 ratingsInstant Apache Camel Messaging System Rating: 0 out of 5 stars0 ratingsSpring Security 3.x Cookbook Rating: 0 out of 5 stars0 ratingsSpring Data Rating: 0 out of 5 stars0 ratingsLearning Vue.js 2 Rating: 0 out of 5 stars0 ratingsGradle for Android Rating: 0 out of 5 stars0 ratings
Internet & Web For You
The $1,000,000 Web Designer Guide: A Practical Guide for Wealth and Freedom as an Online Freelancer Rating: 5 out of 5 stars5/5The Logo Brainstorm Book: A Comprehensive Guide for Exploring Design Directions Rating: 4 out of 5 stars4/5Beginner's Guide To Starting An Etsy Print-On-Demand Shop Rating: 0 out of 5 stars0 ratingsGrokking Algorithms: An illustrated guide for programmers and other curious people Rating: 4 out of 5 stars4/5How To Make Money Blogging: How I Replaced My Day-Job With My Blog and How You Can Start A Blog Today Rating: 4 out of 5 stars4/5Python QuickStart Guide: The Simplified Beginner's Guide to Python Programming Using Hands-On Projects and Real-World Applications Rating: 0 out of 5 stars0 ratingsCoding All-in-One For Dummies Rating: 4 out of 5 stars4/5The Mega Box: The Ultimate Guide to the Best Free Resources on the Internet Rating: 4 out of 5 stars4/5Coding For Dummies Rating: 5 out of 5 stars5/5The Digital Marketing Handbook: A Step-By-Step Guide to Creating Websites That Sell Rating: 5 out of 5 stars5/5The Designer's Web Handbook: What You Need to Know to Create for the Web Rating: 0 out of 5 stars0 ratingsCybersecurity For Dummies Rating: 4 out of 5 stars4/5Everybody Lies: Big Data, New Data, and What the Internet Can Tell Us About Who We Really Are Rating: 4 out of 5 stars4/5200+ Ways to Protect Your Privacy: Simple Ways to Prevent Hacks and Protect Your Privacy--On and Offline Rating: 0 out of 5 stars0 ratingsHow To Start A Profitable Authority Blog In Under One Hour Rating: 5 out of 5 stars5/5How To Start A Podcast Rating: 4 out of 5 stars4/5Mike Meyers' CompTIA Security+ Certification Guide, Third Edition (Exam SY0-601) Rating: 5 out of 5 stars5/5Hacking : The Ultimate Comprehensive Step-By-Step Guide to the Basics of Ethical Hacking Rating: 5 out of 5 stars5/5Six Figure Blogging Blueprint Rating: 5 out of 5 stars5/5Social Engineering: The Science of Human Hacking Rating: 3 out of 5 stars3/5How to Disappear and Live Off the Grid: A CIA Insider's Guide Rating: 0 out of 5 stars0 ratingsThe Internet Is Not What You Think It Is: A History, a Philosophy, a Warning Rating: 4 out of 5 stars4/5Remote/WebCam Notarization : Basic Understanding Rating: 3 out of 5 stars3/5How to Be Invisible: Protect Your Home, Your Children, Your Assets, and Your Life Rating: 4 out of 5 stars4/5Podcasting For Dummies Rating: 4 out of 5 stars4/5Stop Asking Questions: How to Lead High-Impact Interviews and Learn Anything from Anyone Rating: 5 out of 5 stars5/5
Reviews for Hacking with Spring Boot 2.3
2 ratings1 review
- Rating: 1 out of 5 stars1/5book is good, but the code samples is not readable with black background in scribd reader mode.
2 people found this helpful
Book preview
Hacking with Spring Boot 2.3 - Greg Turnquist
Table of Contents
Copyright
Credits
Dedication
Foreword
About the Author
Preface
What this book covers
What you need for this book
Who should read this book
Optimal viewing
Conventions
Reader feedback
Support
Downloading the code
1
Building a Web App with Spring Boot
What is Spring Boot?
Introducing Reactive Programming
Coding with Reactor Types
Say hello to Spring WebFlux
Building an E-Commerce Platform with Spring Boot
Project Parent
Application Metadata
Spring Boot Starters
Spring Boot Maven Plugin
Initial Code
Autoconfiguration
Component Scanning
Creating a Spring WebFlux Controller
Tiptoeing into Templates
Summary
2
Data Access with Spring Boot
Requirements of a Reactive Data Store
Defining Your E-Commerce App’s Domain
Creating a Repository
Loading Test Data
Showing the cart
Adding items to a cart
Wrapping things inside a service
Querying the database
When query derivation isn’t enough
Query by Example
Fluent operations
Trade offs
Summary
3
Developer Tools for Spring Boot
Starting your application…faster
Say hi
to Developer Tools
Automatic restarts and reloads
Exclusion of static resources
Disabling caches in debug mode
Logging extra web activity
Logging of changes in autoconfiguration
LiveReload support
Reactor Developer Tools
Debugging Reactor flows
Logging Reactor flows
Finding blocking code with BlockHound
Summary
4
Testing with Spring Boot
Reactively writing unit tests
Running embedded container tests
Using Spring Boot’s slice testing
Unit testing with BlockHound
Summary
5
Operations with Spring Boot
Deploying your application to production
Going to production with an über JAR
Going to production with Docker
Managing your application in production
Pinging your app with Spring Boot Actuator and /actuator/health
Serving valuable app details with /actuator/info
Accessing additional actuator endpoints
Accessing loggers with /actuator/loggers
Reading operational data
Reading up on threads with /actuator/threaddump
Analyzing data using /actuator/heapdump
Tracing HTTP calls with /actuator/httptrace
Other operational readouts
Customizing management service routes
Summary
6
Building APIs with Spring Boot
Creating an HTTP web service
Creating an API portal
The challenges of API evolution
Creating a hypermedia-based web service
The value of hypermedia
Adding affordances to your API
Summary
7
Messaging with Spring Boot
Picking your favorite solution
Tackling a problem with a familiar pattern
Testing with ease
Coding a solution
Crafting a test case
Wrapping a blocking API call with a custom Scheduler
Coding a consumer
Summary
8
RSocket with Spring Boot
Introduction to RSocket
Creating a reactive protocol
RSocket paradigms
Request/Response
Request/Stream
Fire-and-forget
Channel
Creating an RSocket server
Creating an RSocket client
Converting a WebFlux request into an RSocket request/response
Converting a WebFlux request into an RSocket fire-and-forget
Converting a WebFlux request into an RSocket channel
Summary
9
Securing your Application with Spring Boot
Getting started
Getting real
Taking the driver’s seat
Tapping into user context
Method-level security
OAuth security
Summary
About the Author
Copyright
Hacking with Spring Boot 2.3:
Reactive Edition
© 2020 Greg L. Turnquist
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.
All opinions stated are the author’s and do not necessarily reflect those of the Spring team, Pivotal Software, VMware, Dell EMC, or any other entity. Any usage of Spring
, Spring Boot
, Spring Framework
, Project Reactor
, any other portfolio project, Pivotal
, VMware
, Testcontainers
, RabbitMQ
, Docker,
MongoDB, or any other entity is completely unaffiliated with its owners. Any excerpts and usages thereof are strictly in the spirit of
fair use."
Certain outputs have been edited to fit the format of this book. Nothing of critical value has been left out on purpose.
All rendering and typesetting performed by Asciidoctor, Asciidoctor PDF, and Asciidoctor EPUB3. Fonts include Noto Serif for prose and Fira Code for code. Special thanks to Dan Allen and the Asciidoctor community for their support in making this book possible.
Published: May 2020
Greg L. Turnquist
c/o Hacking with Spring Boot
P.O. Box 4042
Clarksville, TN 37043
USA
GregLTurnquist.com/hacking-with-spring-boot
Credits
Author
Greg L. Turnquist
Foreword
Dr. Dave Syer
Editor
Doug Warren
Cover
AMDesign Studios
Reviewers
Sergei Egorov
Martin Fürstenau
Chua Wen Ching
Dedication
To those that have spoken in front of crowds,
To those that have launched user groups with only two people,
To those that have traveled the globe to share their love of Spring,
To those that were the first at their company to suggest using it,
This is book is dedicated to you,
for you are the true heroes of this rich and vibrant community.
Foreword
Spring Boot has been such a success that it’s probably not wrong now to describe it in 2020 as mainstream.
Practically every Java developer will know something about it, and many, maybe even the majority, will have used it in anger. But there’s always something new to learn, and there are always new problems to solve in software engineering—that’s what makes it so rewarding in the end. There’s always something new to invent, too, and having the skill and opportunity to create code is extremely rewarding, intellectually and in other ways. One of the goals of Spring Boot is shared with the author of this book, and that is to get your ideas down into code as quickly and efficiently as possible, so you can get it to the most special place: Production. I wish you a short and pleasant journey, or maybe a long series of short and pleasant journeys.
In this book, Greg has picked some of the newest ideas in Spring Boot and applied them to some old, well-seasoned favourite problems that you will have experienced as Java developers. What better way to learn something new than to look at it through the lens of tasks that we all have to solve, nearly every day: creating HTTP endpoints, securing them, connecting to databases, writing tests, sending messages? The book adds some new angles to these old chestnuts by applying modern ideas and tools. Read it and you will learn about Reactive Streams, hypermedia, RSocket and OpenID, all from the most practical and pragmatic of standpoints.
There are more things to Spring Boot than just main methods, embedded containers, autoconfiguration and management endpoints. The pure joy of getting started with a fully featured Spring application in a few lines of code cannot be understated, for instance. I invite you to dip into this book, break out an editor or an IDE and crank up some applications for yourself. Greg has been an important member of the Spring Boot team, despite having a day job doing other things in the Spring Engineering effort, and we can be grateful for that as well as the effort he has lavished on this excellent book. He has always been an educator and an informer, as well as an engineer, and this shows through very clearly in the book. When I read it I can hear Greg’s voice, and his personality, very clearly, and it is always calm, but enthusiastic, with a touch of humour. Read it yourself and enjoy—coding with Spring is still fun after all these years!
— Dr. Dave Syer
Senior Consulting Engineer and co-founder of Spring Boot
About the Author
Greg L. Turnquist works on the Spring team as a principal developer at VMware. He is a committer to Spring HATEOAS, Spring Data, Spring Boot, R2DBC, and Spring Session for MongoDB. He also wrote Packt’s best-selling title, Learning Spring Boot 2.0 2nd Edition. He co-founded the Nashville Java User Group in 2010 and hasn’t met a Java app (yet) that he doesn’t like.
Follow him on Twitter @gregturn and subscribe for all his Spring Boot videos at YouTube.com/GregTurnquist.
Preface
What this book covers
Chapter 1, Building a Web App with Spring Boot - Learn how to build web applications using Spring WebFlux.
Chapter 2, Data Access with Spring Boot - Access reactive data stores using Spring Data.
Chapter 3, Developer Tools for Spring Boot - Enhance your developer experience with all the tools afforded by Spring Boot.
Chapter 4, Testing with Spring Boot - Get a hold of reactive testing tools and how Spring Boot empowers testing your applications.
Chapter 5, Operations with Spring Boot - See how to manage your applications after they go to production.
Chapter 6, Building APIs with Spring Boot - Build JSON-based APIs using different tactics and tools from the Spring portfolio.
Chapter 7, Messaging with Spring Boot - Create asynchronous, message-based solutions using Spring Boot and Testcontainers.
Chapter 8, RSocket with Spring Boot - Discover a protocol that has reactive baked right in and supports multiple ways to communicate.
Chapter 9, Securing your Application with Spring Boot - Learn how secure your application with the most powerful tools available.
What you need for this book
Spring Boot 2.3 supports Java 8 and higher. This book is written using Java 8. Use sdkman to install, manage, and even switch between different distributions and versions of Java.
Spring Boot 2.3 is able to bake Docker containers. There is also Docker-based testing support through 3rd party tools like Testcontainers. For those sections, you’ll need to install Docker.
If you use Mac, you should consider Homebrew as an alternative package manager for certain utilities.
You need either an IDE or a good editor. Recommended options include:
IDE
IntelliJ IDEA
Spring Tool Suite
VS Code
Eclipse
Editor
Sublime Text 3
Atom
Who should read this book
This book is to help developers new to Spring Boot as well as experienced Spring developers.
It shows how to get operational, fast, with some of the best coding practices available.
It helps the reader focus on adding business value to their applications and not get distracted with infrastructure.
Optimal viewing
Adjust your e-reader to use a smaller font. This book is loaded with code examples. Attempting to show things too big will cause unneeded wrapping, culminating in a less than desirable experience.
Conventions
In this book, you will find a number of styles of text.
Code found in the text are shown like this: A Spring WebFlux controller is flagged with an @Controller annotation.
A block of code looks like this,
Example block of code
When certain parts of the code are described in more detail, they are annotated with a circled number at the end of the line.
Code with annotated lines
①
This comment describes the line above with the (1) comment.
②
And this is for the (2) line.
③
The (3) line.
④
The lambda expression with (4).
Sometimes you’ll see chunks of code that have comments at the end with no numbering. To improve readability in the code and in the manuscript, line breaks are sometimes forced.
Warnings appear like this.
Tips appear like this.
Notes appear like this.
Important facts appear like this.
Reader feedback
The most valuable feedback you can leave is an honest review.
Please visit your book provider when you finish and share you personal opinion of Hacking with Spring Boot 2.3: Reactive Edition.
Support
If you have issues with getting your copy, contact the provider.
If you are having issues with the code, please file a ticket at https://github.com/hacking-with-spring-boot/hacking-with-spring-boot-code/issues.
If there is an issue with the manuscript, please email me at greg@greglturnquist.com.
Downloading the code
You can download the example code from GitHub at https://github.com/hacking-with-spring-boot/hacking-with-spring-boot-code, free of charge.
Are you ready? Chapter 1, Building a Web App with Spring Boot is waiting!
1
Building a Web App with Spring Boot
Working with Spring Boot is like pair-programming with the Spring developers.
~ Josh Long @starbuxman
Six years ago, something amazing happened. Spring Boot 1.0 was released. On April 1st, 2014, project lead Phil Webb published a blog article detailing the first stable release.[¹]
And the crowd went wild. The Java community embraced this amazing culmination of engineering and creative art with fervent excitement. Searching Twitter for #springboot tweets generated an avalanche of activity.
Three years later, in 2017, the marketing department of Pivotal tweeted that Spring Boot’s download growth had achieved 19.7MM downloads per month.[²]
Something was done. And it was done right.
In this groundbreaking release of Hacking with Spring Boot 2.3: Reactive Edition, you are going to dive head first into all kinds of goodness. You’ll build some features for a shopping cart-e-commerce system. Then you’ll accelerate things chapter by chapter, taking a new angle on building your application. And you’ll use Spring Boot to make it happen.
You’ll explore Spring Boot’s powerful tools to speed up development efforts as well as production-ready, cloud-native features.
If you’ve never used Spring Boot before, get ready for some fun. This book is jam-packed with extra goodies that perhaps you weren’t aware of. Your knowledge will be extended so you can take full advantage of its features.
What is Spring Boot?
Maybe you’ve seen a Spring Boot presentation at a conference or a JUG meeting? Perhaps you’ve encountered a quick-fire demo.
What, exactly, is it?
Spring Boot is a fast, opinionated, portable, and production-ready assembly of the Spring portfolio.
Fast - By making decisions based on many factors including your dependencies, Spring Boot helps you build your app quickly.
Opinionated - Spring Boot makes assumptions based on what it sees. These opinions can easily be overruled when needed. But based on feedback, these pre-made opinions have served the community well.
Portable - Built on top of Java’s de facto standard toolkit, the Spring Framework, Spring Boot apps can be run anywhere a JDK can be found. No need for a certified application server or other vendor-specific product. Build your app, package it up using Boot’s tools, and you’re ready to deploy!
Production Ready - Make no mistake, Spring Boot isn’t vaporware. And it’s not confined to tiny stuff (but it’s great for micro/macro/anysize services!) Spring Boot is real and widely adopted. As an example, check out this blog article from Netflix, one of the largest Java shops out there.
You can also subscribe to my YouTube channel and see my fun videos about Spring Boot.
Using this powerful and widely adopted stack, you’ll build a system with speed AND stability.
In Hacking with Spring Boot 2.3: Reactive Edition you will also explore the new paradigm of reactive programming, introduced in Spring Framework 5.0. As you build bigger and bigger systems with increasing volume of users, you need an approach that is steady and rock-solid. Such high-end systems require the ability to process possibly unlimited streams of data arriving asynchronously and in a non-blocking fashion.
In this chapter you will cover the following topics:
Introducing reactive programming.
Launching an e-commerce platform using https://start.spring.io.
Exploring Spring Boot’s management of third-party libraries.
Running your app inside your IDE with no standalone container.
Building a web layer using Spring WebFlux.
Introducing Reactive Programming
Reactive programming is something that has existed for years. You can find academic papers on facets of it going back to the 1970s. And there have been asynchronous, event-driven programming stacks available for years.
So why hasn’t it been picked up in the mainstream?
Probably because the number of shops needing it has been rather small. But the world is entering a new era. Startups are having to serve content to literally millions of users. International audiences demand around-the-clock operational support. And as cloud-based hosting of applications grows in popularity, the concept of throw some more servers at the problem
isn’t working.
Developers seek more efficient, more consistent usage of existing resources. And there is one approach that addresses this: Reactive Streams.
Reactive Streams is a tiny spec. It’s focus is to define a simple contract between publishers and subscribers. Instead of publishing traffic as fast as possible, subscribers are able to exert control by saying, I’m ready for ten more.
And the publisher only sends the next ten. Think of it as demand control.
Chaining together publishers and subscribers across the enterprise makes it possible to have system-wide backpressure. No more performance surprises, but instead better coordinated management of traffic.
Reactive Streams is so simple, in fact, that it isn’t recommended for application developers. Instead, it’s a foundation for frameworks and a means to achieve interoperability.
Project Reactor is VMware’s implementation of Reactive Streams. With it, it’s possible to achieve reactive programming built with the following aspects:
non-blocking, asynchronous programming model
functional programming style
thread-agnostic concurrency
Throughout this book, you’ll learn more and more about what this means. But bottom line, the Spring portfolio of projects makes it easy to embrace scalable solutions without having to start from scratch.
Coding with Reactor Types
As just mentioned Reactive Streams is based on demand control. Project Reactor implements this using the core type Flux
A Flux