Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Spring: Microservices with Spring Boot
Spring: Microservices with Spring Boot

Spring: Microservices with Spring Boot: Build and deploy microservices with Spring Boot

Arrow left icon
Profile Icon In28Minutes Official
Arrow right icon
€17.99 €26.99
Full star icon Full star icon Empty star icon Empty star icon Empty star icon 2 (1 Ratings)
eBook Mar 2018 140 pages 1st Edition
eBook
€17.99 €26.99
Paperback
€32.99
Subscription
Free Trial
Renews at €18.99p/m
Arrow left icon
Profile Icon In28Minutes Official
Arrow right icon
€17.99 €26.99
Full star icon Full star icon Empty star icon Empty star icon Empty star icon 2 (1 Ratings)
eBook Mar 2018 140 pages 1st Edition
eBook
€17.99 €26.99
Paperback
€32.99
Subscription
Free Trial
Renews at €18.99p/m
eBook
€17.99 €26.99
Paperback
€32.99
Subscription
Free Trial
Renews at €18.99p/m

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

Spring: Microservices with Spring Boot

Chapter 2. Extending Microservices

We built a basic component offering a few services in Lesson 1, Building Microservices with Spring Boot. In this lesson, we will focus on adding more features to make our microservice production ready.

We will discuss how to add these features to our microservice:

  • Exception handling
  • HATEOAS
  • Caching
  • Internationalization

We will also discuss how to document our microservice using Swagger. We will look at the basics of securing the microservice with Spring Security.

Exception Handling

Exception handling is one of the important parts of developing web services. When something goes wrong, we would want to return a good description of what went wrong to the service consumer. You would not want the service to crash without returning anything useful to the service consumer.

Spring Boot provides good default exception handling. We will start with looking at the default exception handling features provided by Spring Boot before moving on to customizing them.

Spring Boot Default Exception Handling

To understand the default exception handling provided by Spring Boot, let's start with firing a request to a nonexistent URL.

Non-Existent Resource

Let's send a GET request to http://localhost:8080/non-existing-resource using a header (Content-Type:application/json).

The following screenshot shows the response when we execute the request:

Non-Existent Resource

The response is as shown in the following code snippet:

    {
      "timestamp": 1484027734491,
      "status...

HATEOAS

HATEOAS (Hypermedia as the Engine of Application State) is one of the constraints of the REST application architecture.

Let's consider a situation where a service consumer is consuming numerous services from a service provider. The easiest way to develop this kind of system is to have the service consumer store the individual resource URIs of every resource they need from the service provider. However, this would create tight coupling between the service provider and the service consumer. Whenever any of the resource URIs change on the service provider, the service consumer needs to be updated.

Consider a; typical web application. Let's say I navigate to my bank account details page. Almost all banking websites would show links to all the transactions that are possible on my bank account on the screen so that I can easily navigate using the link.

What if we can bring a; similar concept to RESTful services so that a service returns not only the data about the requested resource...

Exception Handling


Exception handling is one of the important parts of developing web services. When something goes wrong, we would want to return a good description of what went wrong to the service consumer. You would not want the service to crash without returning anything useful to the service consumer.

Spring Boot provides good default exception handling. We will start with looking at the default exception handling features provided by Spring Boot before moving on to customizing them.

Spring Boot Default Exception Handling

To understand the default exception handling provided by Spring Boot, let's start with firing a request to a nonexistent URL.

Non-Existent Resource

Let's send a GET request to http://localhost:8080/non-existing-resource using a header (Content-Type:application/json).

The following screenshot shows the response when we execute the request:

The response is as shown in the following code snippet:

    {
      "timestamp": 1484027734491,
      "status": 404,
      "error": "Not...

HATEOAS


HATEOAS (Hypermedia as the Engine of Application State) is one of the constraints of the REST application architecture.

Let's consider a situation where a service consumer is consuming numerous services from a service provider. The easiest way to develop this kind of system is to have the service consumer store the individual resource URIs of every resource they need from the service provider. However, this would create tight coupling between the service provider and the service consumer. Whenever any of the resource URIs change on the service provider, the service consumer needs to be updated.

Consider a; typical web application. Let's say I navigate to my bank account details page. Almost all banking websites would show links to all the transactions that are possible on my bank account on the screen so that I can easily navigate using the link.

What if we can bring a; similar concept to RESTful services so that a service returns not only the data about the requested resource, but...

Validation


A good service always validates data before processing it. In this section, we will look at the Bean Validation API and use its reference implementation to implement validation in our services.

The Bean Validation API provides a number of annotations that can be used to validate beans. The JSR 349 specification defines Bean Validation API 1.1. Hibernate-validator is the reference implementation; both are already defined as dependencies in the spring-boot-web-starter project:

  • hibernate-validator-5.2.4.Final.jar

  • validation-api-1.1.0.Final.jar

We will create a simple validation for the createTodo service method.

Creating validations involves two steps:

  1. Enabling validation on the controller method.

  2. Adding validations on the bean.

Enabling Validation on the Controller Method

It's very simple to enable validation on the controller method. The following snippet shows an example:

    @RequestMapping(method = RequestMethod.POST, 
    path = "/users/{name}/todos")
    ResponseEntity<?>...

Documenting REST Services


Before a service provider can consume a service, they need a service contract. A service contract defines all the; details about a service:

  • How can I call a service? What is the URI of the service?

  • What should be the request format?

  • What kind of response should I expect?

There are multiple options to define a service contract for RESTful services. The most popular one in the last couple of years is Swagger. Swagger is gaining a lot of ground, with support from major vendors in the last couple of years. In this section, we will generate Swagger documentation for our services.

The following quote from the Swagger website (http://swagger.io) defines the purpose of the Swagger specification:

Swagger specification creates the RESTful contract for your API, detailing all of its resources and operations in a human and machine readable format for easy development, discovery, and integration.

Generating a Swagger Specification

One of the interesting developments in the last few...

Securing REST Services with Spring Security


All the services we have created up until now are unsecured. A consumer does not need to provide any credentials to access these services. However, all services in the real world are usually secured.

In this section, we will discuss two ways of authenticating REST services:

  • Basic authentication

  • OAuth 2.0 authentication

We will implement these two types of authentication with Spring Security.

Spring Boot provides a starter for Spring Security using spring-boot-starter-security. We will start with adding Spring Security starter to our pom.xml file.

Adding Spring Security Starter

Add the following dependency to your file pom.xml:

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-security</artifactId>
    </dependency>

The Spring-boot-starter-security dependency brings in three important Spring Security dependencies:

  • spring-security-config

  • spring-security-core

  • spring...

Internationalization


Internationalization (i18n) is the process of developing applications and services so that they can be customized for different languages and cultures across the world. It is also called localization. The goal of internationalization or localization is to build applications that can offer content in multiple languages and formats.

Spring Boot has built-in support for internationalization.

Let's build a simple service to understand how we can build internationalization in our APIs.

We would need to add a LocaleResolver and a message source to our Spring Boot application. The following code snippet should be included in Application.java:

    @Bean
    public LocaleResolver localeResolver() {
      SessionLocaleResolver sessionLocaleResolver = 
      new SessionLocaleResolver();
      sessionLocaleResolver.setDefaultLocale(Locale.US);
      return sessionLocaleResolver;
    }

   @Bean
   public ResourceBundleMessageSource messageSource() {
     ResourceBundleMessageSource...

Caching


Caching data from services plays a crucial role in improving the performance and scalability of applications. In this section, we will look at the implementation options that Spring Boot provides.

Spring provides a caching abstraction based on annotations. We will start with using Spring caching annotations. Later, we will introduce JSR-107 caching annotations and compare them with Spring abstractions.

Spring-boot-starter-cache

Spring Boot provides a starter project for caching spring-boot-starter-cache. Adding this to an application brings in all the dependencies to enable JSR-107 and Spring caching annotations. The following code snippet shows the dependency details for spring-boot-starter-cache. Let's add this to our file pom.xml:

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-cache</artifactId>
    </dependency>

Enabling Caching

Before we can start using caching, we need to enable caching...

Left arrow icon Right arrow icon

Key benefits

  • • Get to know the advanced features of Spring Boot in order to develop and monitor applications
  • • Use Spring cloud to deploy and manage microservices on the cloud
  • • Look at embedded servers and deploy a test application to a PaaS Cloud platform
  • • Embedded with assessments that will help you revise the concepts you have learned in this book

Description

Microservices helps in decomposing applications into small services and move away from a single monolithic artifact. It helps in building systems that are scalable, flexible, and high resilient. Spring Boot helps in building REST-oriented, production-grade microservices. This book is a quick learning guide on how to build, monitor, and deploy microservices with Spring Boot. You'll be first familiarized with Spring Boot before delving into building microservices. You will learn how to document your microservice with the help of Spring REST docs and Swagger documentation. You will then learn how to secure your microservice with Spring Security and OAuth2. You will deploy your app using a self-contained HTTP server and also learn to monitor a microservice with the help of Spring Boot actuator. This book is ideal for Java developers who knows the basics of Spring programming and want to build microservices with Spring Boot. This book is embedded with useful assessments that will help you revise the concepts you have learned in this book. This book is repurposed for this specific learning experience from material from Packt's Mastering Spring 5.0 by Ranga Rao Karanam.

Who is this book for?

This book is aimed at Java developers who knows the basics of Spring programming and want to build microservices with Spring Boot.

What you will learn

  • • Use Spring Initializr to create a basic spring project
  • • Build a basic microservice with Spring Boot
  • • Implement caching and exception handling
  • • Secure your microservice with Spring security and OAuth2
  • • Deploy microservices using self-contained HTTP server
  • • Monitor your microservices with Spring Boot actuator
  • • Learn to develop more effectively with developer tools

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Mar 14, 2018
Length: 140 pages
Edition : 1st
Language : English
ISBN-13 : 9781789137897
Vendor :
Oracle
Languages :
Concepts :

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 : Mar 14, 2018
Length: 140 pages
Edition : 1st
Language : English
ISBN-13 : 9781789137897
Vendor :
Oracle
Languages :
Concepts :

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 111.97
Mastering Spring Boot 2.0
€41.99
Spring: Microservices with Spring Boot
€32.99
Spring 5.0 By Example
€36.99
Total 111.97 Stars icon
Banner background image

Table of Contents

4 Chapters
1. Building Microservices with Spring Boot Chevron down icon Chevron up icon
2. Extending Microservices Chevron down icon Chevron up icon
3. Advanced Spring Boot Features Chevron down icon Chevron up icon
4. Assessment Answers Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Empty star icon Empty star icon Empty star icon 2
(1 Ratings)
5 star 0%
4 star 0%
3 star 0%
2 star 100%
1 star 0%
Satyajit Kumar Sethy Jun 03, 2019
Full star icon Full star icon Empty star icon Empty star icon Empty star icon 2
I was thinking to have the Advanced contents,but found very basic, also issue with Amazon Payment, as taken cash as well Internet Banking. so over all i paid double amount. Very dissapointment as the system how allowed 2 times for a single item.
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.