Tuesday 25 February 2020

6 years exp java interview preparation_Microservices

Micro Services

What is OpenShift?

Open source by Red Hat.
combines Kubernetes with a variety of other tools to provide a complete platform for deploying and managing containerized apps.
The main components of modern OpenShift include:

1.Kubernetes, for orchestrating containers.
2.Docker, to provide the execution engine for containers.
3.Open vSwitch, an open source virtual switching tool that provides software-defined networking for OpenShift environments.
4.A Linux distribution (either Red Hat Enterprise Linux [RHEL] or Atomic Host, a version of RHEL) for hosting all of the above.


Docker

Developers could package up their application, including all of the bins and libraries it needs to run correctly, 
into a small container image. In production that container can be run on any computer that has a conterization platform.
How do you pacakge and distribute an application?

Kuberneties:Orchestration means, coordintating and scheduling containers, upgraidnthe applicatns, monitoroing hte conintails,
 if any container gows dow, need to restaer.

 How would all of these containers be coordinated and scheduled? How do you seamlessly upgrade an application without any interruption of service? 
 How do you monitor the health of an application, know when something goes wrong and seamlessly restart it?

 Ho wot yo scale, run, and monitor an application?


docker pull jboss-fuse-6/fis-java-openshift
#docker pull repo2a.cld.uat.dbs.com:5000/openshift3/logstash
#docker pull repo2a.cld.uat.dbs.com:5000/jboss-amq-6/amq63-openshift-mariadb:1.6
docker build -t $module:$version .
oc login -u $THIS_OC_USER -p $THIS_OC_PASSWD $THIS_OC_URL
ocToken=`oc whoami -t`
docker login --username=$THIS_OC_USER -e mohanrajmani@dbs.com --password=$ocToken $THIS_DKR_REGISTRY
docker tag $module:$version $THIS_DKR_REGISTRY/$project/$module:$version
docker push $THIS_DKR_REGISTRY/$project/$module:$version
=====================


Micro services global exception handling


@ControllerAdvice public class CustomizedResponseEntityExceptionHandler extends ResponseEntityExceptionHandler { @Override protected ResponseEntity<Objeact> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatus status, WebRequest request) { Status errorDetail = new Status(StatusConstants.HttpConstants.CUSTOM_FIELD_VALIDATION.getCode(), ex.getBindingResult().getFieldError().getDefaultMessage()); return new ResponseEntity(new Response(errorDetail, null), HttpStatus.BAD_REQUEST); } }

401 --unauthenticated
403-->forbiddedn authenticated but doesnot have access means not authorized


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

Spring cloud config server:
central config server for all micro servere, if we want to update any property we can do that, and it will reflect with out build and deploy or restart the application or microservice, it is done by Actuator refresh REST endpoint

we need to give the servcie ID

With microservices, we create a central config server where all configurable parameters of micro-services are written version controlled. The benefit of a central config server is that if we change a property for a microservice, it can reflect that on the fly without redeploying the microservice.
Before the microservices era, we created a properties files where we maintained our configurable parameters so that if we changed the parameter values or added or deleted a parameter, we generally needed to restart the application container. Moreover, think about the environments. Often, we have Development, Staging, and Prod, and each has separate URL for different services like JMS, JNDI, etc. Also, if the environment changes, we need to pick right properties file. For instance, for development, we need to load the development property file. Spring provides the Profile concept where, based on the passing profile, Spring loads the appropriate environment's properties.
Like if the profile value is dev it loads all {}-dev.properties.

===========

The config server stores each microservice property based on the Service ID. We can configure the microservice Service iD by giving a unique value of spring.application.name property in the bootstrap.properties file for that microservice.
Say I have an Employee Payroll microservice. I can create a Service ID as follows in my Employee Payroll bootstrap.property file.
spring.application.name=EmployeePayroll.

Now, in the config server, we have a set of properties files for Employee Payroll based on environment like
EmployeePayroll-dev.properties
EmployeePayroll-stg.properties
EmployeePayroll-prod.properties


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

Microservices by Eureka


Configuring Eureka Server,

server.port=8086
eureka.client.register-with-eureka=false

@EnableEurekaServer
@SpringBootApplication
public class EurekaServerApplication{
public static void main(String args[]){
SpringApplicaiton.run(EurekaServerApplication.classs,args);
}


@EnableEurekaServer : This annotation configures a registry that allows other applications to communicate.

In client application or in micro service
adding dependencies like EurekaDiscovery

@EnableDiscoveryClient
@SpringBootApplication
public class ClientAplicationMicroService{
      public static void main(String args[]){
}


@EnableDiscoveryClient is basically to register my application in the Eureka Server.
server.port=8081
spring.application.name=client-application-service-->in application.properties file need to add the application name to display the Eureka service.

application.cloud.properties file
eureka.instance.hostname=${applicaitonurl:localhost}
eureka.instance.nonSecure.port=
eureka.instance.metadataMap.instanceId=
eureka.insance.leaseRenewalInervalInSeconds=


eureka.client.region=default
eureka.client.registryfetchIntervalSeconds=
eureka.client.serviceUrl.defalutZone

Another Microservice.
adding dependencies like Eureka Discovery,

Zuul : Zuul provides an intelligent routing system.
Hystrix: It is a Circuit breaker with spring-cloud-net flix Hystrix.
So it is a circuit breaker to stop cascading failures and enables resilience.

add properties in this mircorservice as well.
server.port=8081
spring.application.name=another-client-application-service

@EnableCircuitBreaker
@EnableZuulProxy
@EnableDiscoryClient
@SpringBootApplication
public class AnotherMicroService{
main()

@FeignClient: to interact with the another Microservice.ex: clienApplicaitonMicroservice
to communicat to the other Service

@FeignClient("urlName")
Interface ItemClientOranotherClient{
@GetMapping("/items")
 Resources<Item> readItems();
}

Docker:

Container(application+binaries/libraries)
Docker Engine
OS


Docker Images will create the Docekr Container.
Container will have everything to run an application.

Dokcer is a software to helps to create an image. Image is nothing but a template for a Virtual Machine.and then run instances of that image in a container.

Docker is a tool designed to make it easier to create,build,deploy and run applications by using  containers.

Docker containers are lightweight alternatives to VirtualMachines and it uses the host OS.
You don't have to pre-allocate any RAM in containers.

It does not use guest operating System.it isues host OS unlike VM.
DockerContiner is similar to VirtualMachine but DockerContainer is better than VirtualMachine.

Docker reposity : means vast no .of images, Docker Hub or git repository.


Docker commands:
#systemctl start docker
now pull images from Docker hub.
docker pull: docker pull ubuntu-->first checks local if any images available ,it there are no imags then it go ahead and check it in Docke HUB and pull the image

docker ps: whick will give us the all the images and all the containers which are there in my system.

docker run: docker run -t imageName or (imageId)


Docker Compose:
when we have muliple containers then Docker Compose  makes it easier to configure and run applications that are there in containers.
Docker compose or YML file






Zuul:

How to use Zuul as API Gateway in microservices
Zuul is a front tool for your service instances ,all requests flows through Zuul and then flows to the services.
Zuul can be used as an Authentication,Monitering, routing, filtering and load balancing component.
Zuul uses Ribbon by default for load balancing.


Hystrix is a library created by NetFlix for solving the fault tolerance in a distributed system.
In order to handle failures and do some fall backs when there is a failure. Similar to catch block in a try catch block.


@EnableHystrix-->Even we can do @EnableCircuitBreaker so that we can implement other than Hystrix

@EnableHystrixDashboard
@SpringBootApplication
public class HystrixDashboard{
main()
}









We can use Spring Cloud Hystrix as well.

https://www.youtube.com/watch?v=sPgwbt7iREk

Spring-clould -Net Flix Zuul dependancy.

Zuul API Gateway.

eureka.client.service-url.defalutZone=http://localhost:8761/eureka/

Gloabl exception handling in Microservies

https://www.youtube.com/watch?v=2o7LJLTIgdE

@ControllerAdvice

Micro services:


SpringCloud Server config Or NetFlix Eureka Service Rigistration and discorery  server and client.

Instead of creating many proepteies files for different microserivces, create centra properties file, will automatically buld and deployed with out restaring the server. Or module.


Client-Side Load Balancing
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.

ServerSide load balancing
Server side load balancing can be achieved using Netflix Zuul.

Netflix/HystrixHystrix is a latency and fault tolerance library designed to isolate points of access to remote systems

The Circuit breaker pattern(Hystrix ) helps to prevent such a catastrophic cascading failure across multiple systems. The circuit breaker pattern allows you to build a fault tolerant and resilient system that can survive gracefully when key services are either unavailable or have high latency.

Spring Boot provides actuator endpoints to monitor metrics of individual microservices

Fault tolerance focuses on keeping known error states from causing system failures. Exception handling deals with the undefined and unanticipated conditions that, if left unchecked, can propagate through the system and cause a faultException handling is more like fault avoidance or fault containment.


No comments:

Post a Comment