Create Microservices Architecture Spring Boot

In this Microservices Architecture Spring Boot tutorial we will discuss about to creating a microservices with spring and will see microservices architecture. Microservices allow large systems to be built up from a number of collaborating components. Microservices allows to do loose coupling between application processes in stead of loose coupling between application components as Spring does.

Spring 5 Design Pattern Book

You could purchase my Spring 5 book that is with title name “Spring 5 Design Pattern“. This book is available on the Amazon and Packt publisher website.¬†Learn various design patterns and best practices in Spring 5 and use them to solve common design problems. You could use author discount to purchase this book by using code- “AUTHDIS40“.
Spring-5-Design-Pattern


Microservices Architecture Spring Boot Table of Contents

  1. Introduction
    1. What is Microservices Architecture?
    2. Without Microservices
    3. With Microservices
  2. Microservices Benefits
  3. Microservices Challenges
  4. Microservices Infrastructure
  5. Microservices Tooling Supports
    1. Spring
      1. Spring Boot
    2. Spring Cloud
      1. Eureka by Netflix
  6. Developing Simple Microservices Example
    1. Creating Discovery Service
    2. Creating MicroService (the Producer)
    3. Create Microservice Consumers
  7. Summary

1. Introduction

Microservices is not a new term. It coined in 2005 by Dr Peter Rodgers then called micro web services based on SOAP. It became more popular since 2010. Micoservices allows us to break our large system into number of independent collaborating processes. Lets see below microservices architecture.

1.1 What is Microservices Architecture?

Microservices architecture allows to avoid monolith application for large system. It provide loose coupling between collaborating processes which running independently in different environments with tight cohesion. So lets discuss it by an example as below.

For example imagine an online shop with separate microservices for user-accounts, product-catalog order-processing and shopping carts. So these components are inevitably important for such a large online shopping portal. For online shopping system we could use following architectures.

1.2 Shopping system without Microservices (Monolith architecture)

In this architecture we are using Monolith architecture i.e. all collaborating components combine all in one application.

monolith application architecture

1.3 Shopping system with Microservices

In this architecture style the main application divided in a set of sub applications called microservices. One large Application divided into multiple collaborating processes as below.

Microservices Architecture

Spring enables separation-of-concerns

  • Loose Coupling– Effect of changes isolated
  • Tight Cohesion– Code perform a single well defined task

Microservices provide the same strength as Spring provide

  • Loose Coupling– Application build from collaboration services or processes, so any process change without effecting another processes.
  • Tight Cohesion-An individual service or process that deals with a single view of data.
spring certification

There are a number of moving parts that you have to setup and configure to build such a system. For implementing this system is not too obvious you have to knowledge about spring boot, spring cloud and Netflix. In this post I will discuss one example for this architecture before the example lets first discuss about pros and cons of microservices architecture.
Popular Tutorials

2. Microservices Benefits

  • Smaller code base is easy to maintain.
  • Easy to scale as individual component.
  • Technology diversity i.e. we can mix libraries, databases, frameworks etc.
  • Fault isolation i.e. a process failure should not bring whole system down.
  • Better support for smaller and parallel team.
  • Independent deployment
  • Deployment time reduce

3. Microservices Challenges

  • Difficult to achieve strong consistency across services
  • ACID transactions do not span multiple processes.
  • Distributed System so hard to debug and trace the issues
  • Greater need for end to end testing
  • Required cultural changes in across teams like Dev and Ops working together even in same team.

4. Microservices Infrastructure

  • Platform as a Service like Pivotal Cloud Foundry help to deployment, easily run, scale, monitor etc.
  • It support for continuous deployment, rolling upgrades fo new versions of code, running multiple versions of same service at same time.

5. Microservices Tooling Supports
5.1 Using Spring for creating Microservices

  • Setup new service by using Spring Boot
  • Expose resources via a RestController
  • Consume remote services using RestTemplate

5.2 Adding Spring Cloud and Discovery server
What is Spring Cloud?

  • It is building blocks for Cloud and Microservices
  • It provides microservices infrastructure like provide use services such as Service Discovery, Configuration server and Monitoring.
  • It provides several other open source projects like Netflix OSS.
  • It provides PaaS like Cloud Foundry, AWS and Heroku.
  • It uses Spring Boot style starters

There are many use-cases supported by Spring Cloud like Cloud Integration, Dynamic Reconfiguration, Service Discovery, Security,Client side Load Balancing etc. But in this post we concentrate on following microservices support

  • Service Discovery (How do services find each other?)
  • Client-side Load Balancing (How do we decide which service instance to use?)

Service Discovery
Problem without discovery

  • How do services find each other?
  • What happens if we run multiple instances for a service

 

microservices without discovery server

Resolution with service discovery

 

microservices with discovery server

Implementing Service Discovery

Spring Cloud support several ways to implement service discovery but for this I am going to use Eureka created by Netflix. Spring Cloud provide several annotation to make it use easy and hiding lots of complexity.

Client-side Load Balancing

Each service typically deployed as multiple instances for fault tolerance and load sharing. But there is problem how to decide which instance to use?

Implementing Client-Side Load Balancing

We will use Netflix Ribbon, it provide several algorithm for Client-Side Load Balancing. Spring provide smart RestTemplate for service discovery and load balancing by using @LoadBalanced annotation with RestTemplate instance.

eureka discovery server

@ImageSource-Spring.io


6. Developing Simple Microservices Example

For build a simple microservices system following steps required

  1. Creating Discovery Service (Creating Eureka Discovery Service)
  2. Creating MicroService (the Producer)
    1. Register itself with Discovery Service with logical service.
  3. Create Microservice Consumers find Service registered with Discovery Service
    1. Discovery client using a smart RestTemplate to find microservice.

Maven Dependencies

<dependencies>
  <dependency>
   <groupId>org.springframework.cloud</groupId>
   <artifactId>spring-cloud-starter</artifactId>
  </dependency>
  <dependency>
   <groupId>org.springframework.cloud</groupId>
   <artifactId>spring-cloud-starter-eureka</artifactId>
  </dependency>
  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-web</artifactId>
  </dependency>

  <dependency>
   <groupId>org.hsqldb</groupId>
   <artifactId>hsqldb</artifactId>
   <scope>runtime</scope>
  </dependency>
  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-test</artifactId>
   <scope>test</scope>
  </dependency>
 </dependencies>

Step 1: Creating Discovery Service (Creating Eureka Discovery Service)

  • Eureka Server using Spring Cloud
  • We need to implement our own registry service as below.
discovery-service-application

application.yml

# Configure this Discovery Server
eureka:
  instance:
    hostname: localhost
  client: #Not a client
    registerWithEureka: false
    fetchRegistry: false

# HTTP (Tomcat) port
server:
  port: 1111   

DiscoveryMicroserviceServerApplication.java

package com.doj.discovery;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;

@SpringBootApplication
@EnableEurekaServer
public class DiscoveryMicroserviceServerApplication {

 public static void main(String[] args) {
  SpringApplication.run(DiscoveryMicroserviceServerApplication.class, args);
 }
}

pom.xml

<!-- Eureka registration server -->
  <dependency>
   <groupId>org.springframework.cloud</groupId>
   <artifactId>spring-cloud-starter-eureka-server</artifactId>
  </dependency>

For Whole Source Code for the Discover Server Application you could download from github as below link.

discovery-microservice-server

Run this Eureka Server application with right click and run as Spring Boot Application and open in browser http://localhost:1111/

discovery-service-home-page

Step 2: Creating Account Producer MicroService
Microservice declares itself as an available service and register to Discovery Server created in Step 1.

  • Using @EnableDiscoveryClient
  • Registers using its application name

Lets see the service producer application structure as below.

account microservice application

application.yml

### Spring properties
# Service registers under this name
spring:
  application:
    name: accounts-microservice

# Discovery Server Access
eureka:
    client:
      serviceUrl:
        defaultZone: http://localhost:1111/eureka/

# HTTP Server (Tomcat) Port
server: 
  port: 2222

# Disable Spring Boot's "Whitelabel" default error page, so we can use our own
error:
  whitelabel:
    enabled: false

AccountsMicroserviceServerApplication.java

package com.doj.ms.accounts;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

@SpringBootApplication
@EnableDiscoveryClient
public class AccountsMicroserviceServerApplication {

 public static void main(String[] args) {
  SpringApplication.run(AccountsMicroserviceServerApplication.class, args);
 }
 
}

pom.xml

<dependencies>
  <dependency>
   <groupId>org.springframework.cloud</groupId>
   <artifactId>spring-cloud-starter</artifactId>
  </dependency>
  <dependency>
   <groupId>org.springframework.cloud</groupId>
   <artifactId>spring-cloud-starter-eureka</artifactId>
  </dependency>
  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-web</artifactId>
  </dependency>

 </dependencies>

Other required source files related to this application you could download from github link as given below

accounts-microservice-server

Now run this account service application as Spring Boot application and after few seconds refresh browser to the home page of Eureka Discovery Server at http://localhost:1111/ in previous Step 1. Now one Service registered to the Eureka registered instances with Service Name “ACCOUNT-MICROSERVICE” as below

account microservice

Step 3: Consumer Service

  • Create Consumers to find the Producer Service registered with Discovery Service at Step 1.
  • @EnableDiscoveryClient annotation also allows us to query Discovery server to find miroservices.

Lets see the consumer application structure as below.

application.yml

# Service registers under this name
# Control the InternalResourceViewResolver:
spring:
  application:
    name: accounts-web
  mvc:
    view:
      prefix: /WEB-INF/views/
      suffix: .jsp

# Discovery Server Access
eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:1111/eureka/

# Disable Spring Boot's "Whitelabel" default error page, so we can use our own
error:
  whitelabel:
    enabled:  false
      

WebclientMicroserviceServerApplication.java

package com.doj.web;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

@SpringBootApplication
@EnableDiscoveryClient
public class WebclientMicroserviceServerApplication {
 
 public static final String ACCOUNTS_SERVICE_URL = "http://ACCOUNTS-MICROSERVICE";
 
 public static void main(String[] args) {
  SpringApplication.run(WebclientMicroserviceServerApplication.class, args);
 }
 
 @Bean
 @LoadBalanced
 public RestTemplate restTemplate() {
  return new RestTemplate();
 }
 @Bean
 public AccountRepository accountRepository(){
  return new RemoteAccountRepository(ACCOUNTS_SERVICE_URL);
 }
}

pom.xml

<dependencies>
  <dependency>
   <groupId>org.springframework.cloud</groupId>
   <artifactId>spring-cloud-starter-eureka</artifactId>
  </dependency>
  <dependency>
   <groupId>org.springframework.cloud</groupId>
   <artifactId>spring-cloud-starter-ribbon</artifactId>
  </dependency>
  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-web</artifactId>
  </dependency>
  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-actuator</artifactId>
  </dependency>
  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-test</artifactId>
   <scope>test</scope>
  </dependency>
  <!-- These dependencies enable JSP usage -->
  <dependency>
   <groupId>org.apache.tomcat.embed</groupId>
   <artifactId>tomcat-embed-jasper</artifactId>
   <scope>provided</scope>
  </dependency>
  <dependency>
   <groupId>javax.servlet</groupId>
   <artifactId>jstl</artifactId>
  </dependency>
 </dependencies>

Other required source files related to this application you could download from github link as given below

webclient-microservice-server

Now run this consumer service application as Spring Boot application and after few seconds refresh browser to the home page of Eureka Discovery Server at http://localhost:1111/ in previous Step 1. Now one more Service registered to the Eureka registered instances with Service Name “ACCOUNTS-WEB” as below

Lets our consumer consume the service of producer registered at discovery server.

package com.doj.web;

import java.util.Arrays;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.client.RestTemplate;

/**
 * @author Dinesh.Rajput
 *
 */
public class RemoteAccountRepository implements AccountRepository {
 
 @Autowired
 protected RestTemplate restTemplate;
 
 protected String serviceUrl;
 
 public RemoteAccountRepository(String serviceUrl) {
  this.serviceUrl = serviceUrl.startsWith("http") ? serviceUrl
    : "http://" + serviceUrl;
 }
 
 @Override
 public List<Account> getAllAccounts() {
  Account[] accounts = restTemplate.getForObject(serviceUrl+"/accounts", Account[].class);
  return Arrays.asList(accounts);
 }

 @Override
 public Account getAccount(String number) {
  return restTemplate.getForObject(serviceUrl + "/accounts/{id}",
    Account.class, number);
 }

}

Lets open web application which is a consumer of the account microservice registered at Eureka Discovery Server.

http://localhost:8080/ as below

ms-webclient-service-app

Now click on View Account List then fetch all accounts from account microservice.

http://localhost:8080/accountList

ms-webclient-service-app-2

Now click on any account from the list of accounts to fetch the details of account for account number from account microservice.

http://localhost:8080/accountDetails?number=5115

ms-webclient-service-app-3

Load Balanced RestTemplate
Create using @LoadBalanced– Spring enhances it to service lookup & load balancing

@Bean
 @LoadBalanced
 public RestTemplate restTemplate() {
  return new RestTemplate();
 }

Must inject using same qualifier-

  • If there are multiple RestTemplate you get the right one.
  • It can used to access multiple microservices

 

@Autowired
        @LoadBalanced
 protected RestTemplate restTemplate;


Load Balancing with Ribbon
Our smart RestTemplate automatically integrates two Netflix utilities

  • Eureka Service Discovery
  • Ribbon Client Side Load Balancer

Eureka return the URL of all available instances
Ribbon determine the best available service too use

Just inject the load balanced RestTemplate automatic lookup by logical service-name

7. Summary
After completion of this article you should have learned:

  • What is the MicroServices Architecture
  • Advantages and Challenges of MicroServices
  • And some information about Spring Cloud such as Eureka Discover Server by Netflix and Ribbon.

Spring Boot Related Topics

  1. Spring Boot Interview Questions and Answers
  2. Introduction to Spring Boot
  3. Essentials and Key Components of Spring Boot
  4. Spring Boot CLI Installation and Hello World Example
  5. Spring Boot Initializr Web Interface
  6. Spring Boot Initializr With IDEs
  7. Spring Boot Initializr With Spring Boot CLI
  8. Installing Spring Boot
  9. Developing your first Spring Boot application
  10. External Configurations for Spring Boot Applications
  11. Logging Configuration in Spring Boot
  12. Spring Boot and Spring MVC
  13. Working with SQL Databases and Spring Boot
  14. MySQL Configurations
  15. Spring Data JPA using Spring Boot Application
  16. Spring Boot with NoSQL technologies
  17. Spring Cache Tutorial
  18. Spring Security Tutorial with Spring Boot
  19. Spring Boot and MongoDB in REST Application
  20. Complete Guide for Spring Boot Actuator
  21. Microservices with Spring Boot