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
Mex$179.99 Mex$803.99
Full star icon Full star icon Full star icon Full star icon Empty star icon 4 (22 Ratings)
eBook Nov 2017 370 pages 2nd Edition
eBook
Mex$179.99 Mex$803.99
Paperback
Mex$1004.99
Subscription
Free Trial
Arrow left icon
Profile Icon Greg L. Turnquist
Arrow right icon
Mex$179.99 Mex$803.99
Full star icon Full star icon Full star icon Full star icon Empty star icon 4 (22 Ratings)
eBook Nov 2017 370 pages 2nd Edition
eBook
Mex$179.99 Mex$803.99
Paperback
Mex$1004.99
Subscription
Free Trial
eBook
Mex$179.99 Mex$803.99
Paperback
Mex$1004.99
Subscription
Free Trial

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

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 : 9781786468208
Vendor :
Pivotal
Languages :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

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

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.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
$199.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 Mex$85 each
Feature tick icon Exclusive print discounts
$279.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 Mex$85 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total Mex$ 3,343.97
Spring Boot 2.0 Cookbook
Mex$1004.99
Learning Spring Boot 2.0
Mex$1004.99
Spring Security
Mex$1333.99
Total Mex$ 3,343.97 Stars icon
Banner background image

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

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.