Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Learning Spring Boot 2.0
Learning Spring Boot 2.0

Learning Spring Boot 2.0: Simplify the development of lightning fast applications based on microservices and reactive programming , Second Edition

Arrow left icon
Profile Icon Greg L. Turnquist
Arrow right icon
€18.99 per month
Full star icon Full star icon Full star icon Full star icon Empty star icon 4 (22 Ratings)
Paperback Nov 2017 370 pages 2nd Edition
eBook
€26.98 €29.99
Paperback
€36.99
Subscription
Free Trial
Renews at €18.99p/m
Arrow left icon
Profile Icon Greg L. Turnquist
Arrow right icon
€18.99 per month
Full star icon Full star icon Full star icon Full star icon Empty star icon 4 (22 Ratings)
Paperback Nov 2017 370 pages 2nd Edition
eBook
€26.98 €29.99
Paperback
€36.99
Subscription
Free Trial
Renews at €18.99p/m
eBook
€26.98 €29.99
Paperback
€36.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
Table of content icon View table of contents Preview book icon Preview Book

Learning Spring Boot 2.0

Reactive Web with Spring Boot

The more and more I use #SpringBoot the more I like it.
Derek Stainer @dstainer

In the previous chapter, we saw how quickly an application can be created with just a few lines of code. In this chapter, we are going to embark upon a journey. We will build a social media application where users can upload pictures and write comments.

In this chapter, we will build the web layer for our social media application doing the following:

  • Creating a reactive web application with Spring Initializr
  • Learning the tenets of reactive programming
  • Introducing Reactor types
  • Switching from Apache Tomcat to Embedded Netty
  • Comparing reactive Spring WebFlux against classic Spring MVC
  • Showing some Mono/Flux-based endpoints
  • Creating a reactive ImageService
  • Creating a reactive file controller
  • Showing how to interact with a Thymeleaf template
  • Illustrating how going...

Creating a reactive web application with Spring Initializr

In the last chapter, we took a quick tour through the Spring Initializr site at http://start.spring.io. Let's go back there and pick some basic ingredients to start building our social media site by picking the options needed as shown in the following screenshot:

As shown in the preceding screenshot, we've picked the following options:

  • Build system: Gradle
  • Spring Boot Version: 2.0
  • Group: com.greglturnquist.learningspringboot
  • Artifact: learning-spring-boot

For dependencies, we are going to use these:

  • Reactive Web: This pulls in Reactive Spring, something we'll explore here and through the rest of this book
  • Lombok: This is a tiny library that keeps Java interesting by handling getters, setters, toString, equals, hashCode, and more
  • Thymeleaf: This is not Boot's only supported template library, but...

Learning the tenets of reactive programming

To launch things, we are going to take advantage of one of Spring Boot's hottest new features--Spring Framework 5's reactive support. The entire Spring portfolio is embracing the paradigm of reactive applications, and we'll focus on what this means and how we can cash in without breaking the bank.

Before we can do that, the question arises--what is a reactive application?

In simplest terms, reactive applications engage in the concept of non-blocking, asynchronous operations. Asynchronous means that the answer comes later, whether by polling or by an event pushed backed to us. Non-blocking means not waiting for a response, implying we may have to poll for the results. Either way, while the result is being formed, we don't hold up the thread, allowing it to service other calls.

The side effect of these two characteristics...

Introducing Reactor types

We've mentioned Reactive Streams with little detail. There is a spec for Reactive Streams (http://www.reactive-streams.org/), but it's important to understand that it is quite primitive. In fact, it's so primitive that it's not very effective for building applications. That may sound counterintuitive, but it wasn't written so much for end users as it was for framework developers. To build reactive applications, we'll use Project Reactor (http://projectreactor.io/), the core library that Spring Framework 5 uses for its reactive programming model.

To introduce Reactor's core types, we'll begin with the one we just saw in the previous section, Flux, and some code like this:

    Flux.just("alpha", "bravo", "charlie"); 

This simple creation of a Reactor Flux can be detailed as follows:

    ...

Switching from Embedded Netty to Apache Tomcat

By default, Spring Boot is geared up to use embedded Netty (http://netty.io). Why? Because it's one of the most popular solutions for reactive applications. And when it comes to reactive applications, it's critical that the entire stack be reactive.

However, it's possible to switch to another embedded container. We can experiment with using Apache Tomcat and its asynchronous Servlet 3.1 API. All we have to do is to make some tweaks to the dependency settings in build.gradle, as follows:

    compile('org.springframework.boot:spring-boot-starter-webflux') { 
      exclude group: 'org.springframework.boot', 
      module: 'spring-boot-starter-reactor-netty' 
    } 
    compile('org.springframework.boot:spring-boot-starter-tomcat') 

What's happening in the preceding code? This...

Comparing reactive Spring WebFlux against classic Spring MVC

Ever heard of Spring MVC? It's one of the most popular web frameworks used by the Java community. Since Spring Framework 3, it has utilized an annotation-driven programming style, sometimes known as @MVC.

But we aren't going to use that in this book. Instead, we are going to use something new, Spring WebFlux. WebFlux is an alternative module in the Spring Framework focused on reactive handling of web requests. A huge benefit is that it uses the same annotations as @MVC, along with many of the same paradigms while also supporting Reactor types (Mono and Flux) on the inputs and outputs. This is NOT available in Spring MVC. The big thing to understand is that it's just a module name--spring-webflux versus spring-webmvc.

...

Showing some Mono/Flux-based endpoints

Let's start with a simple HTTP GET. Similar to Spring MVC endpoints, Spring WebFlux supports Flux operations as shown here:

    @GetMapping(API_BASE_PATH + "/images") 
    Flux<Image> images() { 
      return Flux.just( 
        new Image("1", "learning-spring-boot-cover.jpg"), 
        new Image("2", "learning-spring-boot-2nd-edition-cover.jpg"), 
        new Image("3", "bazinga.png") 
      ); 
    } 

This preceding controller can be described as follows:

  • Using the same Flux.just() helper, we return a rather contrived list
  • The Spring controller returns a Flux<Image> Reactor type, leaving Spring in charge of properly subscribing to this flow when the time is right

Before we can move forward, we need to define this Image data type like this:

    @Data...

Creating a reactive ImageService

The first rule of thumb when building web apps is to keep Spring controllers as light as possible. We can think of them as converters between HTTP traffic and our system.

To do that, we need to create a separate ImageService, as shown here, and let it do all the work:

    @Service 
    public class ImageService { 
 
      private static String UPLOAD_ROOT = "upload-dir"; 
 
      private final ResourceLoader resourceLoader; 
 
      public ImageService(ResourceLoader resourceLoader) { 
        this.resourceLoader = resourceLoader; 
      } 
      ... 
    } 

This last Spring service can be described as follows:

  • @Service: This indicates this is a Spring bean used as a service. Spring Boot will automatically scan this class and create an instance.
  • UPLOAD_ROOT: This is the base folder where images will be stored.
  • ResourceLoader: This is...

Creating a reactive file controller

With our reactive image service in place, we can start to work on the reactive file controller.

For starters, let's create a HomeController as shown here:

    @Controller 
    public class HomeController { 
 
      private static final String BASE_PATH = "/images"; 
      private static final String FILENAME = "{filename:.+}"; 
 
      private final ImageService imageService; 
 
      public HomeController(ImageService imageService) { 
        this.imageService = imageService; 
      } 

The preceding code can be described as follows:

  • @Controller: This indicates that it is a web controller, and will be registered by Spring Boot to handle web requests.
  • BASE_PATH: This is a static string used to define the base of many routes.
  • FILENAME: This is a pattern for filenames where the "." is included. Otherwise, Spring...

Why use reactive programming?

At this stage, you've gotten a good taste of how to whip up a file-handling controller, and hitch it to a service that reads and writes files to disk. But the question that often arises is why do I need to do this reactively?

With imperative programming, the process of taking inputs, building intermediate collections and other steps often leaves us with lots of intermediate states--some of it potentially blocking in bad places.

Using the functional style as we've explored so far moves away from the risk of inefficiently building up this state, and switches to building a stream of data instead. And Reactor's operations let us have one stream feed another in lots of different ways. We can merge streams, filter streams, and transform streams.

When we engage in reactive programming, the level of abstraction moves up a level. We find ourselves...

Interacting with a Thymeleaf template

Having put Thymeleaf on the classpath, an entire reactive view resolver has already been configured for us. The last step in putting together the web layer for our social media platform is to create the Thymeleaf template itself. We can do that by putting the following content into index.html underneath /src/main/resources/templates:

    <!DOCTYPE html> 
    <html xmlns:th="http://www.thymeleaf.org"> 
    <head> 
      <meta charset="UTF-8" /> 
      <title>Learning Spring Boot: Spring-a-Gram</title> 
      <link rel="stylesheet" href="/main.css" /> 
    </head> 
    <body> 
 
    <h1>Learning Spring Boot - 2nd Edition</h1> 
 
    <div> 
      <table> 
        <thead> 
        <tr> 
            <th>Id<...

Illustrating how going from async to sync can be easy, but the opposite is not

Invariably, the question comes along--Do I need a synchronous or asynchronous API?

It's important to understand that reactive programming is not very effective unless the entire stack is reactive. Otherwise, we're simply blocking at some point, which causes the backpressure to not achieve much. That's a long-winded way of saying there is little value in making the web layer reactive if the underlying services are not.

However, it is very likely that we may produce a chunk of code that must be tapped by a non-reactive layer, hence, we have to wrap our asynchronous, non-blocking code with the means to block.

Let's explore async-to-sync by creating a BlockingImageService. This service will, basically, leverage the already written ImageService, but not include any of Reactor's Flux...

Summary

We're off to a good start by building the web layer of our social media platform. We used the Spring Initializr to create a bare bones Reactive Spring application with Gradle support. Then we explored the basics of reactive programming by creating a reactive image handling service and wrapping it with a reactive web layer. And we drafted a Thymeleaf template to show thumbnails, allow deleting of images and uploading of new images.

In the next chapter, we will see how to build a data layer and make it reactive as well.

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Get up to date with the defining characteristics of Spring Boot 2.0 in Spring Framework 5
  • Learn to perform Reactive programming with SpringBoot
  • Learn about developer tools, AMQP messaging, WebSockets, security, MongoDB data access, REST, and more

Description

Spring Boot provides a variety of features that address today's business needs along with today's scalable requirements. In this book, you will learn how to leverage powerful databases and Spring Boot's state-of-the-art WebFlux framework. This practical guide will help you get up and running with all the latest features of Spring Boot, especially the new Reactor-based toolkit. The book starts off by helping you build a simple app, then shows you how to bundle and deploy it to the cloud. From here, we take you through reactive programming, showing you how to interact with controllers and templates and handle data access. Once you're done, you can start writing unit tests, slice tests, embedded container tests, and even autoconfiguration tests. We go into detail about developer tools, AMQP messaging, WebSockets, security, and deployment. You will learn how to secure your application using both routes and method-based rules. By the end of the book, you'll have built a social media platform from which to apply the lessons you have learned to any problem. If you want a good understanding of building scalable applications using the core functionality of Spring Boot, this is the book for you.

Who is this book for?

This book is designed for both novices and experienced Spring developers. It will teach you how to override Spring Boot's opinions and frees you from the need to define complicated configurations.

What you will learn

  • Create powerful, production-grade applications and services with minimal fuss
  • Support multiple environments with one artifact, and add production-grade support with features
  • Find out how to tweak your apps through different properties
  • Use custom metrics to track the number of messages published and consumed
  • Enhance the security model of your apps
  • Make use of reactive programming in Spring Boot
  • Build anything from lightweight unit tests to fully running embedded web container integration tests

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Nov 03, 2017
Length: 370 pages
Edition : 2nd
Language : English
ISBN-13 : 9781786463784
Vendor :
Pivotal
Languages :
Tools :

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details

Publication date : Nov 03, 2017
Length: 370 pages
Edition : 2nd
Language : English
ISBN-13 : 9781786463784
Vendor :
Pivotal
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
€189.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
€264.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 122.97
Spring Boot 2.0 Cookbook
€36.99
Learning Spring Boot 2.0
€36.99
Spring Security
€48.99
Total 122.97 Stars icon

Table of Contents

10 Chapters
Quick Start with Java Chevron down icon Chevron up icon
Reactive Web with Spring Boot Chevron down icon Chevron up icon
Reactive Data Access with Spring Boot Chevron down icon Chevron up icon
Testing with Spring Boot Chevron down icon Chevron up icon
Developer Tools for Spring Boot Apps Chevron down icon Chevron up icon
AMQP Messaging with Spring Boot Chevron down icon Chevron up icon
Microservices with Spring Boot Chevron down icon Chevron up icon
WebSockets with Spring Boot Chevron down icon Chevron up icon
Securing Your App with Spring Boot Chevron down icon Chevron up icon
Taking Your App to Production with Spring Boot Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
(22 Ratings)
5 star 54.5%
4 star 9.1%
3 star 18.2%
2 star 18.2%
1 star 0%
Filter icon Filter
Top Reviews

Filter reviews by




Adrimal Dec 17, 2022
Full star icon Full star icon Full star icon Full star icon Full star icon 5
l ensemble est pour moi suffisamment détaillé est clair
Amazon Verified review Amazon
antrophos Apr 23, 2019
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Ich habe die Beispiele gut nachimplementieren können um mir einen Überblick über das neue im Spring zu verschaffen. Das Warum ist im Buch erläutert. Die vollständigen Beispiele gibt es bei Github.
Amazon Verified review Amazon
Richard Dows Mar 29, 2018
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Good book
Amazon Verified review Amazon
Alok Kher Dec 27, 2017
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Well written book. Sample code works. It's cool to see the reactive application up and running in just a few chapters.
Amazon Verified review Amazon
Stephane Maldini Nov 16, 2017
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Greg has spent the last couple of years closely monitoring the Reactive story being prepared by the Spring and Reactor teams. The result ? A book that is offering a pragmatic and progressive path to Spring Boot 2.0 with its new reactive features. It is filled with smart tips that will save reader time more than once. I particularly appreciated the easy mindset bridge between what a Spring developer already knows and what is now offered to him in these latest project iterations. "Learning Spring Boot 2.0" is in my opinion a must-read for the audience looking at empowering modern spring to build efficient backends and microservices. Congrats to the author and I hope this precious resource will help many !
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.