Microservices

Let’s Assume that we have a User and a Department so we can make two services that is User service and Department service.

So, the key is how to manage two different service (user and department),

There is a Service Registry that is the third service where the above two services will be registered and making API gateway where all requests will be received first and will be forwarded to respected services (will work as a mediator)

Currently the Services count we have been is

1) User Service

2) Department Service

3) Service Registry

4) API Gateway

Now the Service 1 and 2 and 4 will be the service which will be registered under Service Registry, A service Registry is a service which keeps track of all the service which are registered to it.

So, for service 1 and 2 that is the user and department service will communicate as independent service, just think you have User service and many of your other project has the usage of user, in fact without user nothing is possible so by this architecture it’s possible that multiple projects can use that same User service.

Other thing is its architecture as an independent service if it curbs down due to server crash or any technical challenges other code will work perfectly as the work with the department service will continue its way.

Now moving on to technicalities

Talking about service 1 and 2 that is the User service and Department service

Make two services from https://start.spring.io/

Add dependencies of your choices like Spring Web, Spring Data JPA, Lombok etc. and add dependency Eureka Discovery Client

The main Dependency you need to add in this project/service is Eureka Discovery Client

The other change you need to make is in the properties file as

=>register-with-eureka: true

=>fetch-registry: true

=>service-url give the URL by the port of the service Registry project that is the 3rd project generally by default we keep 8761 so http://localhost:8761

By doing this it’s clear that we are registering the service 1 and 2 to service 3 that is user and department to Service registry on http://localhost:8761 for the 3rd Service i.e., Service Registry make another project and add dependency Eureka Server.

In this project, in main Application file where you find @SpringBootApplication add an annotation called @EnableEurekaServer which indicates that it’s a service registry.

Another change to indicate it’s as Eureka Service Registry is that you need to add some properties in application.yml file not writing the full property as it will be available in the google in any article properties are register-with-eureka: false and fetch-registry: false

The above two properties will indicate that the server itself didn't need to register as a client.

Now Briefing all above thing

For Microservice we have Independent Services which needs to get registered as client.

Here we took example of user and department two main thing to do annotate with @EnableEurekaClient and the property file configuration register with Eureka and fetch registry to true

Same goes but in opposite for the Service registry that is the 3rd service, the properties configuration register with Eureka and fetch registry to false and @EnableEurekaServer So, we have ready architecture and total number of services we have are 3

Now write some code to create user in user service and create department in department service and get user from user service with the department creating repositories and controller.

So, idea is to have fields like

User (Entity)

id

name

deptId=>id of Dept entity

 Department (Entity)

id

name

Moving further create a department (By Postman or any tool of your choice) and a User giving dept id of already created department.

Now to call a user simply write a get request, but for calling department service from user Service,

we need to make a bean of rest template annotate with @Bean and @loadBalancer

Now from the user service, make a call to dept service by url containing port of dept service take the id of the dept from the user Object, make a Wrapper Object like DeptUser which have both combine fields of user and dept.

Other thing you can simplify this is giving the application name to both service user and department service you can mention in the property file (yaml file) as USER-SERVICE and DEPARTMENT-SERVICE

If for example this is the url say http://localhost:9912/departments/1 where 9912 is the port on which dept service is running and 1 is the id of department can turn to http://DEPARTMENT-SERVICE/departments/1

So, the main relief is that we need not need to remember the port name or host and doing this, will pick up the service by searching the name DEPARTMENT-SERVICE

Now all the requests are going directly to the microservices itself, but we need to manage one common interface where all the requests will be received and there will be redirected to

corresponding microservices so this terminology is called Api Gateway.

The Dependencies you need to add for the Api Gateway service are as below

=>Eureka Discovery Client

=>Gateway

=>Spring Boot Actuator

Now in the main class add @EnableEurekaClient to register in service registry followed by the properties in properties file register-with-eureka: true, fetch-registry: true and Service-uri:http://localhost:8761

Now one more thing we need to do routing configuration in the properties file of this project property is

=>Cloud gateway routes followed by Id, Uri and predicates

=>id will be name of the service that you have given in the particular service that is USER-SERVICE or DEPARTMENT-SERVICE

=>In Uri we need to give lb://USER-SERVICE that means it must be load balanced.

=>predicates have the value as Path=/users/**

/users/** means in the user Controller, one writes in the Request Mapping the uri that we have provided, and it means any request starting from users and ending with anything must be redirected to user service application.

same we need to define for the department service.

So now from wherever you have code for checking the Api’s or from postman for user and dept service calling various rest end points substitute the port of API gateway and you will be able to create users/dept successfully

this means you didn’t need to memorize the ports for all the services registered in Eureka service Registry...!

                                                    Implementing Circuit Breaker

Now let’s move on to the phase while one of the services stops working or fails to give response back in such case, we need something that will be our default response in case if the response fail the default response will be the one which will work for us to implement such kind of thing, we need to implement the Circuit Breaker Pattern in Microservices for that we need Hystrix Library followed by some fallback methods which will work as a default response.

In the API gateway project add the Hystrix[Maintanence] Dependency ,now go to the main file there we will be already having two annotations that is @EnableDiscoveryClient and @SpringBootApplication add the third annotation that is @EnableHystrix.

Now we need to do the Hystrix Configuration so need to create a fallback controller for it where all our fallback methods will be present so whenever the service is down, we will redirect to the Fallback Controller.

Make two methods in the controller one for the user and another for the department these will be fallback methods and will be in picture when any of the service fails to respond.

For that we need to add some properties in application.yml file after the predicates which is the filer property under filter property, we have name and args and under args we again have name and fallbackuri.

so it goes like,

name:CircuitBreaker,args:name:USER-SERVICE and fallbackuri:forward:/userServiceFallback

/userServiceFallback is the uri above method which we have defined under controller named FallBackMethodController.

The same one can be defined for the Department as well it will be name:CircuitBreaker,args:name:DEPARTMENT -SERVICE and fallbackuri:forward:/dept ServiceFallback.

Here /dept ServiceFallback is the uri of the method which we have defined under controller named FallBackMethodController for responding as a default response if any method fails to respond

Now the last configuration is about how much time we need to wait for the response? 

So for that the last property to be added in the properties file is hystrix:command:fallbackcmd:execution:isolation:thread:timeoutInMilliseconds:4000 ,So if service fails to respond and it waits for 4 seconds after this our fallback methods will come in picture and will provide the default response like 

“service unavailable please try again later" or any favorites marked by the user etc.

Try this by bringing down one service stopping the server and observe the results. So this was the circuit breaker implementation for microservices.


Comments

Popular posts from this blog

State space search / blocks world problem by heuristic approach /TIC TAC TOE

Navigation in Vaadin.

Drag and drop items from one Grid to another