Level 2 - Microservices and React.js Notes
Level 2 - Microservices and React.js Notes
1. Spring Microservices
2. React.js
Microservices: they are small independent service which can be developed, test &
deployed independently
Service Discovery: It is a program that registers the microservices, in Spring there’s
a Eureka Server that acts like service discovery
Discovery Client / Microservices: These are the programs which registers in the
service discovery, in Spring there’s Eureka Client that takes care of all the common
jobs of the microservice like:-
a. Automatically registering in the Eureka Server
b. Constantly pinging to the Eureka Server about its health status every 30s
c. Registers to the Eureka Server by default searching in 8761
Pre-requisites
1. Spring Boot 3.x
2. JDK 17 or later
Creating service discovery
1. Eureka Server
application.properties
Creating Microservices
Library:
1. Eureka Client
2. Web
3. Devtools
application.properties
Client Side Load Balancer:
It is a program runs in the microservice to
1. Resolve the actual location of the microservice using the instance-id
2. Distribute the load across the multiple instances of the same instance-id if
there are more than one instance.
@LoadBalanced: This annotation creates the client side load balancer
@LoadBalanced
@Bean
public RestTemplate template() {
return new RestTemplate();
}
@LoadBalanced enables rest template to send request that is distributed across the
multiple instances
We need to autowire the RestTemplate wherever we want to send request to the
remote service
@Autowired
RestTemplate rest;
rest.getForObject(URL, String.class): This sends GET request to the remote service &
converts the response in string format
rest.getForObject(URL, Account.class): This sends GET request to the remote service
& coverts the response in the form of Account object
Wallet Microservice: This will access Account Microservice
Note: OpenFeign is the library which can also make HTTP calls, but it has inbuilt load
balancer, this is provided by spring cloud to simplify the HTTP calls, better than
RestTemplate
We need to create following classes
1. Account: To represent account details
2. Wallet: To represent account & wallet details
3. WalletService: To communicate with the remote service
4. WalletController: To handle the request from the user & call the WalletService
Account.java
Wallet.java
Output:
Drawbacks of RestTemplate
1. It is an older API
2. It can’t be reused like URL need to be repeated
Feign Client
It is used to make remote calls, it is released when spring microservices was
released
- It helps you to reuse the remote calls
- It internally uses the client side load balancer - you don’t need to use
@LoadBalanced
You need to create a reusable interface which helps to create a reusable remote
calls
@FeignClient(“http://ACCOUNT-SERVICE”)
interface Client {
@GetMapping(“/account/{accountNumber}”)
public Account getAccount(@PathVariable(“accountNumber”) long
accountNumber);
}
Calling getAccount sends a GET request to the remote microservice, the return type
tells the response must be converted to which object ex: JSON to Account object
Note: You don’t have to implement this interface, spring boot automatically
implements the interface we only need to use @EnableFeignClients to let spring
boot implement the interface
@EnableFeignClients: This scans all the @FeignClient interface & lets spring boot to
implement that interface & register the implemented object in the spring container
Client.java
We need to mention @EnableFeignClients in the main class so that this interface will
be implemented using LoadBalancer behind the scene.
Change the service layer to use the FeignClient interface instead of RestTemplate
application.properties
Now the client program should get the configurations from the configuration server
by mentioning the configuration server URL & also which configuration file it needs
Firstly you need to add config client library
Update the account-service/pom.xml
account-service/application.properties
Day 2 Agenda
1. Encrypting & Decrypting sensitive data
2. Circuit breaker pattern
3. Reactive Programming using Web Flux
4. Spring Security
configuration-server/application.properties
Now you can use /encrypt & /decrypt url to encrypt the data.
In the properties you need to use {cipher} beside the encrypted data so that the
configuration server will decrypt the data and give them to the microservices
account-service.properties
// fallback method must have the same signature with a Throwable parameter
public Wallet getAccount2(long acc, Throwable t) { } // fallback method gets called
automatically if remote service is down or circuit breaker state is open
In application.properties you will configure the failure rates, threshold, for the
getAccount (name of the CircuitBreaker)
ex: resilence4j.circuitbreaker.instance.getAccount.threshold=50 #50% failure is the
threshold
Reslience4j uses RingBit buffer to track the failures
Ring bit buffer is a memory to track the success & failures, success will be entered
with 0 & failures will be entered 1, based on these numbers it identifies the failure
%.
Note: AOP may not be available in spring initializr, you need to get it from the
Maven
Note: We need to configure the circuit breaker in the wallet service
wallet-service/pom.xml
WalletService.java
application.properties
Programs to launch
1. Service Discovery
2. Configuration Server
3. Account Microservice
4. Wallet Microservice
You can see the circuit breaker status in /actuator/health
Stop the Account Service and send few more requests minimum 5, then you can see
the OPEN state
1. After 1 min you can see HALF_OPEN
2. HALF_OPEN to CLOSE state occurs only if the service is up
Activity:
Account Microservice should connect to the MySQL database using Spring Data JPA,
however the datasource configurations must be pulled from the GIT and also the
username & password must be in encrypted format, when wallet sends the account
number it has to send only those numbers present in the database
Steps:
1. Using configuration server create the encrypted data for username &
password & store them in your git repository (ensure you are able push the
configuration file whose name matches to the spring.application.name of
account service)
2. Add Spring Data JPA & MySQL library to the account microservice
3. Create an entity for account and map the account number & balance
4. Create a Repository that extends JpaRepository<Account, Long>
5. From the service layer you must get the Account balance using the account
number
6. From the controller call the service layer method and return account number
& balance in JSON format
Spring Security
Authentication: Verify the user
Authorization: Permissions for the user to access the resource
OAuth2: It is a token generated for Authentication & Authorization, but it is not a
standard token
JWT: JSON Web Token, it follows some standards like Digital signature and encoding
formats
Add User
Generate the token
We will create a service layer that performs the operations synchronously &
asynchronously, which returns multiple user objects.
User.java
UserService.java
UserController.java
Output:
React.js
It is a Javascript library used to develop User Interfaces for Single Page Applications.
Single Page Applications are those applications where everything happens in one
single page.
Javascript
It is a programming language used to develop User interfaces, all browsers
understand Javascript, it takes care of adding dynamic effect to the web pages,
other than Javascript browser understands HTML & CSS
HTML: Displaying the content
CSS: Style the HTML
Javascript: Provide effects to the HTML & CSS at runtime
Arrays & Iterations
String padding: whenever you want to add some extra strings in the beginning or
end of a string you can use methods like
- padStart()
- padEnd()
998877XXXX: padding at the end
XXXX998833: padding in the beginning
Optional chain
It is used when you are accessing a property of an object which may or may not be
present, earlier developers used if conditions to check for the property in the object,
but it makes the code lengthier, which you can also check using ?.
let arrays = [ { id: 200, name : “Sid”, address : { state: “KA”, city : “BLR” } },
{id: 300, name: “Chinmay”},
{ id: 300, name : “Vivek”, address : { state: “MH”, city : “MBI” }}
];
forEach -> item.name, if(item.address != ‘undefined’) { item.address.state } //
older approach
// newer approach is to use ?.
forEach -> item.name, item.address?.state
Virtual DOM (VDOM): It updates the Real DOM without refreshing the entire DOM
tree by making changes only to the content that needs the change
npm start >> package.json >> runs a script file for start
How to share the data from one component to another component in React.js
We can share the data in two ways
1. props: read-only data
2. state: read & write both
Every component will have an inbuilt property called props to receive the value from
another component
If App wants to share an object to User: App -> object -> User
Then App component can share like this:-
<User name = “Alex” age = “25” /> Here props = {name = “Alex”, age = “25” }
<User name = “Raj” age = 35” /> Here props = {name = “Raj”, age = “35” }
In User component you can read name & age through props
function User(props) {
name = props.name;
age = props.age
Display name & age
}
A component can also share a complex objects or array to the props
let object = {id:100, name:”Raj”, salary:35000}
<Employee obj = {object} />
function Employee(props) {
let e = props.obj; // e = obj = object = {id:100, name:”Raj”, salary:35000}
}
Simple.js
How to iterate array of elements in React.js
You will use List & Keys: List is a collection of iterated item inside an element & key
is an unique id for each iterated item
In React.js you need to call the map function and create element for each iteration
let fruits = [“Orange”, “Mango”, “Grapes”, “Apple”];
let list = fruits.map( (fruit, index) => <li key = {index}>{fruit}</li>);
<ol> { list } </ol> This results in
<ol>
<li key = “0”>Orange</li>
<li key = “1”>Mango</li>
<li key = “2”>Grapes</li>
<li key = “3”>Apple</li>
</ol>
You can also iterate inside the HTML element as below
<ol>
{ fruits.map((fruit, index) => <li key = {index}>{fruit}</li>) }
</ol>
Adding styles in the React.js
You can add an online CDN link in a global stylesheet index.css or you can download
the css library and add its path in the index.css(recommended, because it will part
of the project)
npm install bootstrap >> This downloads the bootstrap inside node_modules
index.css
@import url(path of bootstrap in node_modules)
Installing bootstrap
Note: bootstrap provides 10000+ inbuilt classes, in React.js we must use className
as an attribute instead of class, because class is a keyword in Javascript
<p class = ‘text-danger’> is incorrect inside the JSX, we must use
<p className = ‘text-danger’>
You can also add your own styles using style attribute
Programmatic navigation
import { useNavigate } from ‘react-router-dom’;