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
$19.99 per month
Full star icon Full star icon Empty star icon Empty star icon Empty star icon 2 (1 Ratings)
Paperback Mar 2018 140 pages 1st Edition
eBook
$24.99 $35.99
Paperback
$43.99
Subscription
Free Trial
Renews at $19.99p/m
Arrow left icon
Profile Icon In28Minutes Official
Arrow right icon
$19.99 per month
Full star icon Full star icon Empty star icon Empty star icon Empty star icon 2 (1 Ratings)
Paperback Mar 2018 140 pages 1st Edition
eBook
$24.99 $35.99
Paperback
$43.99
Subscription
Free Trial
Renews at $19.99p/m
eBook
$24.99 $35.99
Paperback
$43.99
Subscription
Free Trial
Renews at $19.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

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

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 $5 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 $5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total $ 147.97
Spring 5.0 By Example
$48.99
Spring: Microservices with Spring Boot
$43.99
Mastering Spring Boot 2.0
$54.99
Total $ 147.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

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.