Microservices Architecture with Spring Boot in 15mins

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.
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.

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




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
  1. <dependencies>
  2.   <dependency>
  3.    <groupId>org.springframework.cloud</groupId>
  4.    <artifactId>spring-cloud-starter</artifactId>
  5.   </dependency>
  6.   <dependency>
  7.    <groupId>org.springframework.cloud</groupId>
  8.    <artifactId>spring-cloud-starter-eureka</artifactId>
  9.   </dependency>
  10.   <dependency>
  11.    <groupId>org.springframework.boot</groupId>
  12.    <artifactId>spring-boot-starter-web</artifactId>
  13.   </dependency>
  14.   <dependency>
  15.    <groupId>org.hsqldb</groupId>
  16.    <artifactId>hsqldb</artifactId>
  17.    <scope>runtime</scope>
  18.   </dependency>
  19.   <dependency>
  20.    <groupId>org.springframework.boot</groupId>
  21.    <artifactId>spring-boot-starter-test</artifactId>
  22.    <scope>test</scope>
  23.   </dependency>
  24.  </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
  1. # Configure this Discovery Server
  2. eureka:
  3.   instance:
  4.     hostname: localhost
  5.   client: #Not a client
  6.     registerWithEureka: false
  7.     fetchRegistry: false
  8. # HTTP (Tomcat) port
  9. server:
  10.   port: 1111  

DiscoveryMicroserviceServerApplication.java
  1. package com.doj.discovery;
  2. import org.springframework.boot.SpringApplication;
  3. import org.springframework.boot.autoconfigure.SpringBootApplication;
  4. import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
  5. @SpringBootApplication
  6. @EnableEurekaServer
  7. public class DiscoveryMicroserviceServerApplication {
  8.  public static void main(String[] args) {
  9.   SpringApplication.run(DiscoveryMicroserviceServerApplication.class, args);
  10.  }
  11. }

pom.xml
  1. <!-- Eureka registration server -->
  2.   <dependency>
  3.    <groupId>org.springframework.cloud</groupId>
  4.    <artifactId>spring-cloud-starter-eureka-server</artifactId>
  5.   </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
  1. ### Spring properties
  2. # Service registers under this name
  3. spring:
  4.   application:
  5.     name: accounts-microservice
  6. # Discovery Server Access
  7. eureka:
  8.     client:
  9.       serviceUrl:
  10.         defaultZone: http://localhost:1111/eureka/
  11. # HTTP Server (Tomcat) Port
  12. server:
  13.   port: 2222
  14. # Disable Spring Boot's "Whitelabel" default error page, so we can use our own
  15. error:
  16.   whitelabel:
  17.     enabled: false

AccountsMicroserviceServerApplication.java
  1. package com.doj.ms.accounts;
  2. import org.springframework.boot.SpringApplication;
  3. import org.springframework.boot.autoconfigure.SpringBootApplication;
  4. import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
  5. @SpringBootApplication
  6. @EnableDiscoveryClient
  7. public class AccountsMicroserviceServerApplication {
  8.  public static void main(String[] args) {
  9.   SpringApplication.run(AccountsMicroserviceServerApplication.class, args);
  10.  }
  11.  
  12. }

pom.xml
  1. <dependencies>
  2.   <dependency>
  3.    <groupId>org.springframework.cloud</groupId>
  4.    <artifactId>spring-cloud-starter</artifactId>
  5.   </dependency>
  6.   <dependency>
  7.    <groupId>org.springframework.cloud</groupId>
  8.    <artifactId>spring-cloud-starter-eureka</artifactId>
  9.   </dependency>
  10.   <dependency>
  11.    <groupId>org.springframework.boot</groupId>
  12.    <artifactId>spring-boot-starter-web</artifactId>
  13.   </dependency>
  14.  </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
  1. # Service registers under this name
  2. # Control the InternalResourceViewResolver:
  3. spring:
  4.   application:
  5.     name: accounts-web
  6.   mvc:
  7.     view:
  8.       prefix: /WEB-INF/views/
  9.       suffix: .jsp
  10. # Discovery Server Access
  11. eureka:
  12.   client:
  13.     serviceUrl:
  14.       defaultZone: http://localhost:1111/eureka/
  15. # Disable Spring Boot's "Whitelabel" default error page, so we can use our own
  16. error:
  17.   whitelabel:
  18.     enabled:  false

WebclientMicroserviceServerApplication.java
  1. package com.doj.web;
  2. import org.springframework.boot.SpringApplication;
  3. import org.springframework.boot.autoconfigure.SpringBootApplication;
  4. import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
  5. import org.springframework.cloud.client.loadbalancer.LoadBalanced;
  6. import org.springframework.context.annotation.Bean;
  7. import org.springframework.web.client.RestTemplate;
  8. @SpringBootApplication
  9. @EnableDiscoveryClient
  10. public class WebclientMicroserviceServerApplication {
  11.  
  12.  public static final String ACCOUNTS_SERVICE_URL = "http://ACCOUNTS-MICROSERVICE";
  13.  
  14.  public static void main(String[] args) {
  15.   SpringApplication.run(WebclientMicroserviceServerApplication.class, args);
  16.  }
  17.  
  18.  @Bean
  19.  @LoadBalanced
  20.  public RestTemplate restTemplate() {
  21.   return new RestTemplate();
  22.  }
  23.  @Bean
  24.  public AccountRepository accountRepository(){
  25.   return new RemoteAccountRepository(ACCOUNTS_SERVICE_URL);
  26.  }
  27. }

pom.xml
  1. <dependencies>
  2.   <dependency>
  3.    <groupId>org.springframework.cloud</groupId>
  4.    <artifactId>spring-cloud-starter-eureka</artifactId>
  5.   </dependency>
  6.   <dependency>
  7.    <groupId>org.springframework.cloud</groupId>
  8.    <artifactId>spring-cloud-starter-ribbon</artifactId>
  9.   </dependency>
  10.   <dependency>
  11.    <groupId>org.springframework.boot</groupId>
  12.    <artifactId>spring-boot-starter-web</artifactId>
  13.   </dependency>
  14.   <dependency>
  15.    <groupId>org.springframework.boot</groupId>
  16.    <artifactId>spring-boot-starter-actuator</artifactId>
  17.   </dependency>
  18.   <dependency>
  19.    <groupId>org.springframework.boot</groupId>
  20.    <artifactId>spring-boot-starter-test</artifactId>
  21.    <scope>test</scope>
  22.   </dependency>
  23.   <!-- These dependencies enable JSP usage -->
  24.   <dependency>
  25.    <groupId>org.apache.tomcat.embed</groupId>
  26.    <artifactId>tomcat-embed-jasper</artifactId>
  27.    <scope>provided</scope>
  28.   </dependency>
  29.   <dependency>
  30.    <groupId>javax.servlet</groupId>
  31.    <artifactId>jstl</artifactId>
  32.   </dependency>
  33.  </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.

  1. package com.doj.web;
  2. import java.util.Arrays;
  3. import java.util.List;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.web.client.RestTemplate;
  6. /**
  7.  * @author Dinesh.Rajput
  8.  *
  9.  */
  10. public class RemoteAccountRepository implements AccountRepository {
  11.  
  12.  @Autowired
  13.  protected RestTemplate restTemplate;
  14.  
  15.  protected String serviceUrl;
  16.  
  17.  public RemoteAccountRepository(String serviceUrl) {
  18.   this.serviceUrl = serviceUrl.startsWith("http") ? serviceUrl
  19.     : "http://" + serviceUrl;
  20.  }
  21.  
  22.  @Override
  23.  public List<Account> getAllAccounts() {
  24.   Account[] accounts = restTemplate.getForObject(serviceUrl+"/accounts", Account[].class);
  25.   return Arrays.asList(accounts);
  26.  }
  27.  @Override
  28.  public Account getAccount(String number) {
  29.   return restTemplate.getForObject(serviceUrl + "/accounts/{id}",
  30.     Account.class, number);
  31.  }
  32. }

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
  1. @Bean
  2.  @LoadBalanced
  3.  public RestTemplate restTemplate() {
  4.   return new RestTemplate();
  5.  }

Must inject using same qualifier- 

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

  1. @Autowired
  2.         @LoadBalanced
  3.  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.

Comments

DevOps said…
The information which you have provided in this blog is really useful to everyone. Thanks for sharing.
Microservices Online Training
Anonymous said…
Very nice post with lots of information. Thanks for sharing this
Microservices Online Training
Microservices Training in Hyderabad
Bhanu Sree said…

This is an amazing blog, thank you so much for sharing such valuable information with us.
Microservices Online Training
Microservices Training in Hyderabad
Nooble said…
Watch our video for microservices spring cloud tutorial which serves the configurations from a repository along with three microservices and a gateway application that routes the request.
siva sreedhar said…
I like your post very much. It is very useful for my research. I hope you can share more info about this. Keep posting
Workday Integration training
Workday Studio training
Tableau online training
Tableau Server training
Tableau Advanced training
ETL Testing Training
Gaurav Singh said…
Thank you for sharing such a beautiful information with us. I hope you will share more info about Microservices. Please keep sharing.
microservices online training
workday said…
Thank you for sharing wonderful information with us to get some idea about it..workday studio online training india
workday studio training india
Kaparthicynixit said…
Thank You for Sharing this wonderful and much required information in this post.
Visit us: Dot Net Training Online India
Visit us: .Net Online Training Hyderabad
rustamkhan said…
microservice architecture

Transform your legacy application with a microservices architecture that breaks your application into small components independent from each other.

to get more - https://www.nitorinfotech.com/services/microservices/
rustamkhan said…
microservice solutions

Transform your legacy application with a microservices architecture that breaks your application into small components independent from each other.

to get more - https://www.nitorinfotech.com/services/microservices/
workday said…
Thank you for sharing wonderful information with us to get some idea about it.

workday online training hyderabad
workday online training in india
Sarika A said…
I feel very grateful that I read this. It is very helpful and very informative and I really learned a lot from it. We are also providing the best services click on below links to visit our website.
Oracle Fusion HCM Training
Workday Training
Okta Training
Palo Alto Training
Adobe Analytics Training
Danny Cooper said…
Very Informative and creative contents. This concept is a good way to enhance the knowledge. thanks for sharing. Continue to share your knowledge through articles like these, and keep posting on

Data Engineering Services 

Artificial Intelligence Solutions

Data Analytics Services

Business Intelligence Solutions
Allen Marry said…
IT's very informative blog and useful article thank you for sharing with us , keep posting learn more about Product engineering services | Product engineering solutions.
cyber pc said…
thank you a lot for sharing this all-powerful weblog.Very inspiring and harmonious to steer too.wish you still allocation more of your ideas.i will definitely love to gate.! Virtual Audio Cable Cracked
cyber pc said…
thanks for assisting human beings income the information they mannerism. brilliant stuff as pleasing. preserve up the massive take feature!!!! Tally ERP 9 Crack

Popular posts from this blog

PostgreSQL bytea and oid

MySQL as Hive metadata store

Big Memory Go.