You are on page 1of 29

Micro Services

Micro Services:
1) Monolith Introduction
2) Monolith Architecture case study
3) Monolith Application Development Process
4) Load balancer(Cluster)case study
5) Load Balancing Algorithm(a.Round Robin, b)IP Hashing, c)Sticky Session)
6) Monolith Drawbacks
7) Micro Services Introduction
8) Micro Services Advantages
9) Micro Services Dis-Advantages
10) Micro Services Case study
11) Micro Services Architecture
12) Micro Services Development(a.API-1, b.API-2)
13) Inter service communication case study
14) Feign Client
15) Cloud Introduction.(AWS,AZURE,PCF)
16) PCF CLI Installation
17) Deploying Micro Services to PCF using CLI
18) Auto Scaling
19) Service Registry case study(Netflix Edurekha)
20) API Gateway(Zuul Proxy)
21) Hystrix(Circuit Breaker)
22) Hystrix Dashboard
23) Spring Boot Admin services.

Load Balancer & LB Algos

----------------------------------------------------

-> When all components are in same application, all requests come to same server then burden
will increase on server.

-> When burden increased on server, it will process requests slowly sometimes server might get
crash also.

-> To reduce burden on the server, people will use Load Balancers for applications.

-> Our application will be deployed to multiple servers and all those servers will be connected
Load balancer.
How Load Balancer will distribute the load?

--------------------------------------------

LBR will use algorithm to distribute incoming to requests to servers.

1) Round Robbin

2) Sticky Session

3) IP Hashing etc....

Monolith Architecture:
 In our application , we will have several modules and several components also will be
available
Components:
> Presentation components: Responsible for handling user interface
> Web components: Responsible to handle user requests.
> Business components: Responsible to execute Business logic.
> Persistence components: Responsible for DB operation.
> Integration components : Responsible webservices Rest-Api
communications.
> Authorization components : Responsible to authorizing user
> Notification Components : Responsible for sending email/mobile message
notification whenever required.
 If we develop all these components as a single project then it is called as monolith
Architecture Based Project.

Benefits of monolith Architecture:


 Simple for development : at initial stage very easy
 Easy for testing : End to end testing we can perform
 Easy for deployment : one WAR file only we can have to deploy
 Easy for scaling : Multiple servers we can spin easily
Draw backs of Monolith Arhitecture :
 Maintenance : If application is too large and complex to understand, making changes for
enhancements and CR is very difficult(Lot of impact analysis is required)
 Adopting to new technology is very difficult
 The size of the application can reduce application startup time
 Realiability : if there is bug in one module, then it leads to entire application will go down.
 We must re-deploy entire application when we make some changes to code.
 Quick releases are not possible.
 New team members can’t understand the project easily.

Microservices Architecture :
 Microservice is an architectural design pattern which is used to avoid the problems of
monolith Architecture.
Challenges:
1)Bounded context.
2)Lot of configuration.
3) Visibility
4) Pack of card problem

Advantages:
 Easy maintenance
 Fats releases(Delivery)
 Easy Scale
 Technology independently
 Parallel Development.

Microservices Architecture:
 There is no fixed architecture available for microservices
 People are using microservices Architecture as per their convience

Generalized Microservice Architecture:


1) Service Registry.
2) Services(Rest APIS)
3) API gateway
What is service Registry?
 Service Registry is used to register services available in our project
 Service Registry will provide a dashboard with services information like Status, Health and
URL etc…
 One Service nothing but one rest API.
 We can use Eureka Server as a service registry
Services:
 Rest APIs are called Services in Microservice Based Projects
 Rest APIs contains business logic to perform Business operation
 As part of business operation one rest API can communicate with another rest API.
 Microservice Based project means it is collection of rest APIs.

API GateWay :

 An api gateway is an API management tool that sits between a client and collection of
backend services.
 API gateways acts ad single Entry point for all clients.
 In API gateway we can write the logic to filter user requests.

Procedure to create service registry


-> Create Spring Boot application with below dependencies
1)spring-boot-starter-web
2)netflix-eureka-server (this is from spring cloud)
-> At spring boot start class specify @EnableEurekaServer annotation
-> Configure Embedded Container port number as 8761.
Note: 8761 is default port number for Eureka. If port is 8761 clients can auto detect eureka
server and will get registered. If port number is not 8761 then we have to register clients
manually.

-> Run our Spring Boot Application and Access Eureka Dashboard using below URL

http://localhost:8761/
Procedure to create Service as Eureka Client
1) Create Spring Boot Project with below dependencies
1) spring-starter-web
2) spring-cloud-netflix-eureka-client
2) Configure @EnableDiscoveryClient annotation at Spring Boot start class
3) Create Rest Controller with Required methods
4) Change Embedded Container Port No if Required and Run application
5) Verify Eureka Dashboard ( Client should be registered )
Eureka Client
-> Service registry is used to register all services available in our project (REST APIs)
-> Service registry will provide a dashboard with details of services which are registered (name,
status & URL)
-> Eureka Server we are using as a Service Registry
-> If Eureka is running on 8761 then then Discovery Clients can auto register with Eureka Server

Developing Second Service as Eureka Client


-> Create Spring Boot app with below dependencies
- spring-boot-starter-web
- spring-cloud-netflix-eureka-client
-> Use @EnableDiscoveryClient annotation at boot start class
-> Create RestController with required methods
-> Configure embedded container port number & application name
-> Run our client application
-> Verify Eureka Server Dashboard (Client should be registered)

Note: Before running client application, make sure Eureka Server Project is Running.

---------------------Eureka Client yml file------------------------


server:
port: 2222
spring:
application:
name: HELLO-SERVICE
eureka:
client:
service-url:
defaultZone: ${DISCOVERY_URL:http://localhost:9761}/eureka/
--------------------------------------------------------------------
Note: 9761 is Service Registry Project Port Number

FeignClient for Interservice Communication


-> We have created below 3 applications
1) Service-Registry (Port Number : 8761) - Eureka Server
2) HI-SERVICE (Port Number : 1111) - Eureka Client-1
3) HELLO-SERVICE (Port NumBer : 2222) - Eureka Client-2

Inter-Service Communication
In our project, if one micro-services accessing another microserice then it is called as Inter-
service communication.
Note: Both Microservices are available in Same Project.
-> We can use Rest Client logic to access one Rest API

Working with FeginClient


<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
----------------------------------------------------------------
package com.ashokit.client;

import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
@FeignClient(name = "HELLO-SERVICE")
public interface HelloClient {

@GetMapping(value = "/hello/{name}")
public String invokeHelloService(@PathVariable("name") String name);

Microservices Requirement
-> If one microservices is communicating with another microservice belongs to same project is
called as Inter Service Communication.
-> For Inter Service Communication we can use FeignClient
-> When we use FeignClient, we can specify name of the service instead of URL for
communication

Stock App implementation


StockPriceService : This service is responsible to take company name as an input and return stock
price of that company as output . (It is a rest api). This service will maintain companies stock prices
in Embedded db.

Steps to develop
1) Create boot application with below dependencies
a) spring-boot-starter-web
b) h2
c) project lombok
d) devtools
e) spring-boot-starter-data-jpa
f) swagger & swagger-ui

2) Create Entity class & Repository interface


3) Create data.sql file with insert queries (src/main/resources)
4) Create Service interface & implementation
5) Create Rest Controller
6) Configure Swagger documentation

Exception Handling using @ControllerAdvice


@ControllerAdvice
public class StockPriceServiceExceptionMapper{

@ExceptionHandler(value=CompanyNameNotFoundException.class)
public ResponseEntity<String> handleNotFoundException(){
String mug = "Company Name Not Found";
return new ResponseEntity(mug, HttpStatus.OK);
}
}
----------------------------------------------------------------

StockAmountCalculationService
This rest api will take company name and quantity as input. It should get company stock price from
'StockPriceService' api. Then it has to calculate total price for given quantity and it has to return that
as an output.

Steps to develop Stock-Amt-Calc-Service


1) create spring boot application with below dependencies
a)spring-boot-starter-web
b)spring-cloud-starter-open-feign
c)devtools
2) Create FeignClient to access 'StockPriceService'
3) Create RestController with required method
4) Configure port number, application-name in yml file

Steps to Develop UI application


1) Create Spring Boot application with below dependencies
1) spring-boot-starter-webflux
2) tomcat embed jasper
3) devtools
2) Create Service class to access 'Stock-Calculation-Service' using webclient
3) Create Controller with required methods
4) Create View File
5) configure port number and view resolver
6) Run our application

Steps to Configure FeignClient


1) Add spring-cloud-starter-openfeign in pom.xml
2) Enable Feign Clients using @EnableFiegnClients annotation at boot start class
3) Create a interface for FeginClient and use @FeignClient annotation

Use Case
Develop a project to Calculate stock price
API Gateway Implementation
-> API Gateway will act as Entrypoint services available in project
-> API Gateway will be called as Edge Microservice
-> If we don't have API Gateway then we need to implement request filtering logic in every
microservice. It increases Maintenense cost of the project.
-> Spring Cloud Netflix Library provided Zuul Proxy as an API Gateway.
-> Zuul Proxy is open source API Gateway
-> Apigee is commercial API Gateway provided by Google

Steps to develop API Gateway


1) Create Spring Boot Application with below dependencies
a) spring-boot-starter-web
b) spring-cloud-netflix-zuul
c) spring-cloud-netflix-eureka-client
2) Configure @EnableZuulProxy & @EnableDiscoveryClient annotations at Spring Boot start class
3) Configure API Gateway with Eureka Server Registration in yml
4) Configure Routing to access backend services in yml
4) Configure application name and port number
Mini Project Execution Flow
-> API Gateway is an API management tool which handles all incoming requests to our backend
service
-> API Gateway sits between client requests and backend services
-> Spring Cloud Netflix library provided 'Zuul Proxy' as an API Gateway. It is an open source.

Stock Application Using Microservices Architecture


SERVICE-REGISTRY : http://localhost:8761/
STOCK-PRICE-SERVICE : http://localhost:1111/price/stockprice/{cname}
STOCK-CALC-SERVICE: http://localhost:2222/calc/calculate/{cname}/{qty}
API-GATEWAY : http://localhost:4444/api/

URLS given to our clients


To Get Company Price : http://localhost:4444/api/price/price/stockprice/{cname}
To get total cost : http://localhost:4444/api/calc/calc/calculate/{cname}/{qty}

Actuators
-> We are developing applications using Spring Boot and We are deploying our applications in
servers
-> Once application is deployed, several users will access our applications
-> When our application is running in production, it is very important to monitor our application

What is Application Monitoring


-> Health Check
-> Beans check
-> configProps check
-> Heap Dump
-> Thread Dump
-> Http Trace etc......
-> To monitor our applications easily, Spring Boot provided Actuators.
-> Actuators are used to provide 'Production Ready Features' for our application.

Working with Actuators


-> We need to add spring-boot-starter-actuator dependency in pom.xml file
-> Actuators provided several pre-defined endpoints to monitor our application. They are
1) health
2) info
3) beans
4) mappings
5) configProps
6) httpTrace
7) heapdump
8) threaddump
9) shutdown ( It is special endpoint )

-> To access actuator endpoints we should use /actuator as prefix


Ex : http://localhost:9090/actuator/health
-> In Spring Boot 1.x v '/actuator' should not be there in URL
-> In Spring Boot 2.x v '/actuator' is mandatory in URL to access Actuator endpoints
-> When we add 'actuator' starter, by default it will expose 2 endpoints they are 'health' and 'info'
(we can access them directley).
-> To expose all the endpoints we shuld write below property
management:
endpoints:
web:
exposure:
include: *
Actuators in Spring Boot
-> Actuators are used to provide production ready features of our application.
-> Using Actuators we can monitor and manage our applications
-> Actuator endpoints are available to get information about application
-> Below are the few actuator endpoints
health
info
env
beans
mappings
httptrace
threadump
heapdump
shutdown etc...

-> By default health & info endpoints are exposed.


-> heapdump endpoint is used to down jvm heap details. To analyze heap dump files we can use
MAT (Memory analyzer tool).
-> threaddump endpoint provides information about threads available in our application.

-> Shutdown endpoint is a special endpoint. It is used to stop the application.


-> This shutdown endpoint by deafult in disable state.
-> shutdown endpoint is binded to HTTP POST Request.
Spring Boot Admin Server & Admin Client
-> In Microservices Architecture based project, we will have several services (REST APIs)
-> To monitor Rest APIs, we will enable and expose actuator endpoints
-> If we have more no.of services, it will would be very difficult to monitor and manage all our
services available in project.

*** To overcome this problem, Spring Boot Provided Admin Server & Admin Client Concept **

-> If we use Admin Server, it will provide beautiful user interface to monitor and manage our REST
APIs.
Note: Our Rest apis should be registered with Admin server then our rest api is called as Spring Boot
Admin Client.
Example on Admin Server & Client

-> Spring Boot Admin server is used monitor and manage our client applications (rest apis)

-> By using Admin server at one place we can monitor and manage all our services

Steps to Create Admin Server Application

-> Create Spring Boot Application with below dependencies

1)spring-boot-starter-web

2)spring-boot-starter-admin-server

-> Configure @EnableAdminServer in Spring Boot Start class

-> Configure embedded container port number in application.yml file

-> Run application and access dashboard

Note: By default Admin server will provide UI for monitoring and managing registered clients.

Steps to develop Admin Server Client Application

-> Create Spring Boot Application with below dependencies

1)spring-boot-starter-web
2)spring-boot-starter-admin-client

3)spring-boot-starter-actuator

-> Configure below properties in application.yml file

1)port number

2)application name

3)register with admin server

4)expose actuator endpoints

-> Create Rest Controller with Required Methods

-> Run the application and verify Admin Server Dashboard

Note: Client application should be displayed in Admin Server Dashboard.

Working with yml files

-> YML stands for Yet Another Markup Language (YAML)

-> It is used to store the data

-> Earlier people used to work with properties files but now people are using YAML or YML files to
store the data

->To avoid hardcoding in java classes we will use YML files in Spring Boot

Syntax

server:

port: 9090

Note: Indent spaces are very important in yml files

----------------Reading data from YML-------------------------


server:

port: 9090

spring:

application:

name: DEMO-APP

demo:

welcomeMsg: Hello, How are you doing ??

greetMsg: Hi, Good Morning..!!

-----------------------------------------------------------------

@Data

@Configuration

@ConfigurationProperties(prefix = "demo")

@EnableConfigurationProperties

public class DemoConfigProps {

private String welcomeMsg;

private String greetMsg;

--------------------------------------------------------------------

@RestController

public class DemoRestController {

@Autowired

private DemoConfigProps configProps;

@GetMapping("/welcome")

public String welcome() {

return configProps.getWelcomeMsg();

}
@GetMapping("/greet")

public String greetMsg() {

return configProps.getGreetMsg();

Working with Yml or Yaml files

YAML -> Yet Another Markup Language

-> YML files are widely used format for configuration properties

-> Spring Boot is having very good integration with YML files.

-> In Spring Boot we can use .properties and .yml files for configuration properties

-> When we create Spring Boot application, by default it will provide application.properties file

-> We can read YML file data into java bean.

------------------------------------------------------------------

-> Spring Cloud Provied Config Server

-> Config Server is used to Externalize Configuration Properties from our application.

Scenario:> Microservice ----> Config-Server ----> Git Repo

Steps to work with Config Server Project

1) Create Spring Boot application with below dependencies

a) spring-boot-starter-web

b) spring-cloud-config-server

2) Configure @EnableConfigServer annotation at Spring Boot Start class

3) Create GIT repository and create config-properties files in repository then configure properties in
the form of key and vale format.

EX: https://github.com/TEK-Leads/Config-Properties.git

4) Configure below properties in application.properties or application.yml file

a) server-port
b) spring.cloud.config.server.git.uri=<repo-url>

c) spring.cloud.config.server.git.cloneOnStart=true

d) management.security.enabled=false

Steps to develop Config Server Client--

1) Create Spring Boot application with below dependencies

a)spring-boot-starter-web

2)spring-cloud-starter-config

2) Configure below properties in application.properties or application.yml file

a) server-port

b) application-name

c) activate profile

d) spring.cloud.config.uri (It is used to connect with config server)

3) Inject properties values into variables wherever it is required

@Value("${mug}")

Ex: String mug;

Yesterday's session: Config Server In microservices

---------------------------------------------------

application.properties or application.yml file

----------------------------------------------------------

bootstrap.properties or bootstrap.yml file

Q) When to use application.yml and when to use bootstrap.yml

If we have both application.yml and bootstrap.yml in our application, Spring Boot will load
bootstrap.yml first.

-> In bootstrap.yml we will configure, application-name, config-server-url etc.

Circuit Breaker

-> Circuit Breaker is used to protect us from damages.

-> A circuit breaker is an automatically operated electrical switch designed to protect an electrical
circuit from damage caused by excess current from an overload or short circuit. Its basic function is
to interrupt current flow after a fault is detected.
How it is related to Spring Boot ?

-> Using Spring Boot, we are developing Microservices in Java.

-> When we follow Microservices architecture, we will have several services.

-> Our Services are nothing but Rest APIs.

Ribbon in Microservices

-> By Using Ribbon we can achieve Client Side Load Balancing.

-> For Running Spring Boot application we will configure Port Number in application.properties or
application.yml file

Ex : server.port = 9090

-> We don't configure port number, it will consider 8080 as default port number.

-> Using Environment obj, we can capture on which port number our application is running.

-------------------------------------------------------------------------

@RestController

public class WelcomeRestController {

@Autowired

private Environment env;

@GetMapping("/welcome")

public String welcomeMsg() {

String mug = "Welcome to REST API...!!";

String serverPort = env.getProperty("local.server.port");

mug = msg.concat(" I am from Server Which is running on Port :: " + serverPort);


return mug;

----------------------------------------------------------------------------------------------

-> We can pass port number to Spring Boot application as VM argument.

Right Click On Project -> Run As -> Run Configuration -> Click on Arguments Tab -> Write below
property in VM Arguments -> Click on Apply -> Click Run

-Dserver.port=9091

==================================================================================
===========

First Run with -Dserver.port=5050 ===> http://localhost:5050/welcome

Second Run with -Dserver.port=6060 ===> http://localhost:6060/welcome

Third Run with -Dserver.port=7070 ==> http://localhost:7070/welcome

Working with Ribbon in Stock Market Application

================================================

1) Create Service Registry project with Eureak Server

2) Create STOCK-PRICE-SERVICE as Eureka Client

3) Run STOCK-PRICE-SERVICE with 3 instances

4) Create STOCK-CALCULATION-SERVICE USING FeignClient & Ribbon Client

PCF Workshop @ 4 PM IST Today

Zoom Meeting ID: 860 9598 8081

PCF (Pivotal Cloud Foundry)

What is Cloud Computing?


Cloud Computing is the delivery of on-demand computing services - from applications to storage and
processing power.

Cloud Computing works based on pay-as-you-go concept

To celebrate one function in house, we don't purchase shamiyana materal. we will take for rent and
will use for our function. After function got completed, we will return that materal by paying rent
amount.

To develop one application, we need computer, we need OS, we need some softwares like JIRA,
JENKINS, Database, Application Server etc... Instead of purchasing all these softwares, we can take
them for rent on reantal basis.

Based on our usage, we need to pay rent for those softwares.

There are several Cloud Provieders Available in Market

AWS (Amazon Webservices)

Azure (Microsoft)

PCF (Pivotal Cloud Foundry)

GCP (Google Cloud)

IBM Cloud etc....

Cloud Computing is categorized into 3 types

1) IaaS : Infrastructure as a service

Ex: AWS EC2

2) SaaS : Software as a service

Ex : Google Apps, DropBox

3) PaaS : Platform as a service

Ex : PCF

Circuit Breaker

-> Circuit Breaker is used to implement Fault Tolerance

-> In Microservices Architecture, multiple services will be available.

-> If one microservice is not able to process the request, then request processing can't be
completed.....

-> To implement Circuit breaker, we will use Spring Cloud Netflix Hystrix Library
Steps to work with Circuit Breaker

1) Create Spring Boot Application with below dependencies

1)spring-boot-starter-web

2)spring-cloud-starter-netflix-hystrix

2) Configure @EnableCircuitBreaker annotation at Spring Boot Start Class

3) Create Rest Controller with Required Methods (business operation method and fallback method)

4) Configure Circuit Breaker for Business Operation method using below annotation

@HystrixCommand(fallBackMethod="...")

5) Configure port number and run our application.

Distributed Logging using Sleuth & ZipKin

-> Logging is the process of storing application execution details in a file to monitor in future.

-> By using log files we can understanad where is the problem and what is the problem in
application.

Steps to implement Distributed logging using Slueth & Zipkin

1) Download zipkin server (it is jar file)

URL to download : https://zipkin.io/pages/quickstart

2) Run the zipkin server jar file from cmd

Syntax : java -jar <zipkin-jar-file-name.jar>

3) After zipkin server started, access Zipkin dashboard using below url

URL : http://localhost:9411/zipkin/

Note: With this zipkin server setup is done

4) Create Spring Boot Application with below dependencies

1)spring-boot-starter-web

2)sleuth

3)zipkin
4)devtools

5) Create one Rest controller with required methods

6) Implement logging in rest controller methods

------------------------------------------------------------------

@RestController

public class WelcomeRestController {

Logger logger = LoggerFactory.getLogger(WelcomeRestController.class);

@GetMapping(value = "/welcome")

public String getWelcomeMsg() {

logger.info(" **** getWelcomeMsg( ) execution started ****");

String mug = "Welcome to Ashok IT...!!";

logger.info(" **** getWelcomeMsg( ) execution ended ****");

return mug;

-------------------------------------------------------------------

7) Configure Port Number and Run Boot application

8) Send the request to Rest controller method and verify Zipkin dashboard for log details.

Cache Implementation

-> Cache is a temporary storage

-> Whenever we need to access same data frequently then its better to maintain that data in cache
to improve performance of application.

-> If we read same data for multiple times from db it will decrease performance of the application.
Because DB interaction is costly operation.

Q) Can we store all db tables data in Cache Memory?

-> In database we will have 2 types of tables

1) Transactional Tables

2) Non Transaction Tables

What is Transactional Table?


If table data is getting inserted/updated/deleted from the application then it is called as
Transactional table.

What is Non-Transactional Table?

If application is performing only read operation on the table then that table is called as Non-
Transactional table.

Note: We should implement cache for Non-Transactional table because these tables contains static
data

-> If we implement cache in one project, then it is called as Local Cache. Only that project can access
data from that local cache. It is suitable for Monolith Architecture Based Projects.

-> When we implement project using Microservices architecture we will have multiple services. If we
want cache data in all services we should go for Global Cache. It is also called as 'Distributed Cache'.

-> If we implement distributed cache, all services can access data from distributed cache only.

-> Now a days in industry, we are using Redis Cache to maintain Distributed Cache.

What is Redis?

Redis is an open source (BSD licensed), in-memory data structure store, used as a database, cache
and message broker.

It supports data structures such as strings, hashes, lists, sets, sorted sets with range queries,
bitmaps, hyperloglogs, geospatial indexes with radius queries and streams.

Setting Up Redis Server in Windows Machine

1) Download Redis Software from below URL

URL : www.github.com/microsoftarchive/redis/releases

2) Extract Downloaded zip file and open folder structure

3) Execute redis-server.exe file to start redis server in our machine.

4) Execute redis-client.exe file to start redis client cli

5) Once Redis Client CLI is started just execute 'ping' it should give PONG as response.

Note: With above steps Redis software setup is done in our machine
Command to store data in Redis in the form of KEY and VALUE

SET KEY "VALUE"

Ex: SET UNAME "Ashok"

Command to get data from redis using KEY

GET "KEY"

Ex: GET "UNAME"

Command to get all keys from REDIS Server

KEYS

Configuring Multiple Databases in Spring Boot

-> We discussed Spring Data JPA to perform DB operations

-> While Working with Spring Data JPA we used Repositories

-> Using Data JPA Repositories we can perform DB Operations

1) CrudRepository (I)

2) JpaRepository (I)

Components

-----------

Entity class : Mapping DB table

-----------------------------------------

@Entity

@Table(name="USER_TBL")

public class User{

@Id

@Column(name="USER_ID")

private Integer userId;

@Column(name="USER_NAME")

private String userName;

}
---------------------------------------------

Repository interface : Providing methods to do operations

----------------------------------------------------------

public interface UserRepository extends JpaRepository<UserEntity,


Serializable>{

-----------------------------------------------------------------

application.properties or application.yml : DataSource config props

-------------------------------------------------------------------

spring.datasource.url=

spring.datasource.username=

spring.datasource.password=

spring.datasource.driver-class-name=

-> When we configure DataSource config props in application.properties file or application.yml file
Spring Boot will take care of DB connections.

Configuring 2 Data Sources in Spring Boot

----------------------------------------

-------------------application.properties-----------------------

#Oracle Data Source for Users Data

spring.user.datasource.url=

spring.user.datasource.username=

spring.user.datasource.password=

spring.user.datasource.driver-class-name=

#MySql DataSource For Books Data


spring.book.datasource.url=

spring.book.datasource.username=

spring.book.datasource.password=

spring.book.datasource.driver-class-name=

------------------------------------------------------------------

package com.ashokit.config;

import java.util.HashMap;

import javax.persistence.EntityManagerFactory;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Qualifier;

import org.springframework.boot.context.properties.ConfigurationProperties;

import org.springframework.boot.jdbc.DataSourceBuilder;

import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

import org.springframework.data.jpa.repository.config.EnableJpaRepositories;

import org.springframework.orm.jpa.JpaTransactionManager;

import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;

import org.springframework.transaction.PlatformTransactionManager;

import org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration

@EnableTransactionManagement

@EnableJpaRepositories(

entityManagerFactoryRef = "bookEntityManagerFactory",

transactionManagerRef = "bookTransactionManager",

basePackages = {

"com.ashokit.book.repository"

public class BookDBConfig {


@Bean(name = "bookDataSource")

@ConfigurationProperties(prefix = "spring.book.datasource")

public DataSource dataSource() {

return DataSourceBuilder.create().build();

@Bean(name = "bookEntityManagerFactory")

public LocalContainerEntityManagerFactoryBean
bookEntityManagerFactory(EntityManagerFactoryBuilder builder,

@Qualifier("bookDataSource") DataSource dataSource) {

HashMap<String, Object> properties = new HashMap<>();

properties.put("hibernate.hbm2ddl.auto", "update");

return builder.dataSource(dataSource)

.properties(properties)

.packages("com.ashokit.book.model")

.persistenceUnit("Book")

.build();

@Bean(name = "bookTransactionManager")

public PlatformTransactionManager
bookTransactionManager(@Qualifier("bookEntityManagerFactory") EntityManagerFactory
bookEntityManagerFactory) {

return new JpaTransactionManager(bookEntityManagerFactory);

-------------------------------------------------------------

package com.ashokit.config;

import java.util.HashMap;
import javax.persistence.EntityManagerFactory;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Qualifier;

import org.springframework.boot.context.properties.ConfigurationProperties;

import org.springframework.boot.jdbc.DataSourceBuilder;

import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

import org.springframework.context.annotation.Primary;

import org.springframework.data.jpa.repository.config.EnableJpaRepositories;

import org.springframework.orm.jpa.JpaTransactionManager;

import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;

import org.springframework.transaction.PlatformTransactionManager;

import org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration

@EnableTransactionManagement

@EnableJpaRepositories(

entityManagerFactoryRef = "entityManagerFactory",

basePackages = {

"com.ashokit.user.repository"

public class UserDBConfig {

@Primary

@Bean(name = "dataSource")

@ConfigurationProperties(prefix = "spring.user.datasource")

public DataSource dataSource() {

return DataSourceBuilder.create().build();

}
@Primary

@Bean(name = "entityManagerFactory")

public LocalContainerEntityManagerFactoryBean
entityManagerFactory(EntityManagerFactoryBuilder builder,

@Qualifier("dataSource") DataSource dataSource) {

HashMap<String, Object> properties = new HashMap<>();

properties.put("hibernate.hbm2ddl.auto", "update");

return builder.dataSource(dataSource)

.properties(properties)

.packages("com.ashokit.user.model")

.persistenceUnit("User")

.build();

@Primary

@Bean(name = "transactionManager")

public PlatformTransactionManager
transactionManager(@Qualifier("entityManagerFactory") EntityManagerFactory
entityManagerFactory) {

return new JpaTransactionManager(entityManagerFactory);

You might also like