Showing posts with label MicroServices. Show all posts
Showing posts with label MicroServices. Show all posts

Wednesday, 10 June 2020

Microservices Interview Questions Part-1

1. Advantages and disadvantages of micro-services. Why to go for micro services architecture over monolithic architecture.

The Advantages of Microservices
The advantages of microservices seem strong enough to have convinced some big enterprise players such as Amazon, Netflix, and eBay to adopt the methodology. Compared to more monolithic design structures, microservices:
       Improve fault isolation: Larger applications can remain mostly unaffected by the failure of a single module.
       Eliminate vendor or technology lock-in: Microservices provide the flexibility to try out a new technology stack on an individual service as needed. There won’t be as many dependency concerns and rolling back changes becomes much easier. With less code in play, there is more flexibility.
       Ease of Understanding: With added simplicity, developers can better understand the functionality of a service.

The Disadvantages of Microservices
Microservices may be a hot trend, but it does not come without its drawbacks.
Here’s a list of some potential pain areas associated with microservices designs:
       Developing distributed systems can be complex. Since everything is now an independent service, you have to carefully handle requests traveling between your modules. In one such scenario, developers may be forced to write extra code to avoid disruption. Over time, complications will arise when remote calls experience latency.
       Multiple databases and transaction management can be painful.
       Testing a microservices-based application can be cumbersome. In a monolithic approach, we would just need to launch our WAR on an application server and ensure its connectivity with the underlying database. With microservices, each dependent service needs to be confirmed before testing can occur.
       Deploying microservices can be complex. They may need coordination among multiple services, which may not be as straightforward as deploying a WAR in a container. Of course, with the right kind of automation and tools, all the above drawbacks can be addressed.

2. What are Discovery Register in Microservices Architecture?
In the microservices world, Service Registry and Discovery play an important role because we most likely run multiple instances of services and we need a mechanism to call other services without hardcoding their hostnames or port numbers. In addition to that, in Cloud environments service instances may come up and go down anytime. So we need some automatic service registration and discovery mechanism. Spring Cloud provides Service Registry and Discovery features, as usual, with multiple options. We can use Netflix Eureka or Consul for Service Registry and Discovery.

3. What are the Container in microservices?
Containers are packages of your software that includes everything that it needs to run, like code, dependencies, libraries, binaries, and more. Docker is one of the popular choices for building and running containers, but Kubernetes is quickly becoming the standard that is used to orchestrate multiple containers in enterprise environments. Compared to Virtual Machines, containers share the OS kernel instead of having a full copy of it – like making multiple VMs in a single host. Although it is possible to put your microservices in multiple VMs, containers are commonly used in this case since it takes up less space and is faster to boot up.

4. How Communication between Microservices happens.
 There are two ways that I know of through which you can communicate with other Microservices
       Rest Template
       Feign Client

5. Difference Between Rest Template and Feign Client.
RestTemplate is used for making the synchronous call. When using RestTemplate, the URL parameter is constructed programmatically, and data is sent across to the other service. In more complex scenarios, we will have to get to the details of the HTTP APIs provided by RestTemplate or even to APIs at a much lower level.
Feign is a Spring Cloud Netflix library for providing a higher level of abstraction over REST-based service calls. Spring Cloud Feign works on a declarative principle. When using Feign, we write declarative REST service interfaces at the client and use those interfaces to program the client. The developer need not worry about the implementation.

6. List the Microservices design patterns?
1.Aggregator Microservice
In its The simplest form, Aggregator would be a simple webpage that invokes multiple services to achieve the functionality required by the application.
2.Chained Microservice Design Pattern
Chained microservice design pattern produce a single consolidated response to the request. In this case the request from the client received by Service A, which then Communicating with service B, which in turn may be communicating with service C. All are likely using a synchronous HTTP request / response messaging.
3.Branch Microservice Design Pattern
Branch microservice design pattern extends Aggregator design pattern and allows simultaneous response processing from two likely mutually exclusive, chains of microservices. This Pattern can also be used to call different chains, or a single chain based on the business needs.
4.Shared Data Microservice Design Pattern
One of the design principles of microservice is autonomy. That means the service is full-stack and has control of all the components-UI, middleware, persistence, transaction. This allows the service to be polyglot and use the right tool for the right job. For example, if a No Sql data store can be used if that is more appropriate instead of jamming that data in Sql Database.
However, a typical problem, especially when refactoring from an existing monolithic application, is a database normalization such that each microservice has the right amount of data- nothing less and nothing more. Even if only a sql database is used in the monolithic application, deformalizing the database would lead to duplication of data and possibly inconsistency. In a transaction phase some applications may benefit from a shared data microservice design pattern.
In this design pattern, some microservices are likely in a chain, may share caching and database stores. This would only make sense if there is a strong coupling between two services. Some might consider this an anti-pattern but business needs might require in some cases to follow this. This would certainly be an anti-pattern for greenfield applications that are based upon microservices.
5.Asynchronous Messaging Microservice Design pattern
While Rest design pattern is quite prevalent, and well understood, but it has the limitation of being synchronous and thus blocking asynchrony can be achieved but that is done in application specific way. Some microservice architectures may elect to use message queues instead of rest request/response because of that.
6.Proxy Microservice Design Pattern
Proxy microservice design pattern is a variation of aggregator. In this case no aggregation needs to happen on the client but a different microservice may be invoked based on the business needs.
7.Event Sourcing Microservice Design Pattern
The event sourcing design pattern creates events regarding the changes in the application state. Also, these events are stored as a sequence of events to help the developers track which change was made when. So, with the help of this, you can always adjust the application state to cope up with the past changes. You can also query these events, for any data change and simultaneously publish these events from the event store. Once the events are published, you can see the changes of the application state on the presentation layer.
8.Circuit Breaker Pattern
As the name suggests, the Circuit Breaker design pattern is used to stop the process of request and response if a service is not working. So, for example, let’s say a client is sending a request to retrieve data from multiple services. But, due to some issues, one of the services is down. Now, there are mainly two problems you will face: first, since the client will not have any knowledge about a particular service being down, the request will be continuously sent to that service. The second problem is that the network resources will be exhausted with low performance and bad user experience.
9.Command Query Responsibility Segregator (CQRS) Design Pattern
Every microservices design has either the database per service model or the shared database per service. But, in the database per service model, we cannot implement a query as the data access is only limited to one single database. So, in such scenario you can use the CQRS pattern. According to this pattern, the application will be divided into two parts: Command and Query.
10.Decomposition Design Pattern
Microservices are developed with an idea on developers mind to create small services, with each having their own functionality. But, breaking an application into small autonomous units has to be done logically. So, to decompose a small or big application into small services, you can use the Decomposition patterns.

7. What is Containerization?
Containerization is a lightweight alternative to full machine virtualization that involves encapsulating an application in a container with its own operating environment. This provides many of the benefits of loading an application onto a virtual machine, as the application can be run on any suitable physical machine without any worries about dependencies.
Containerization has gained recent prominence with the open-source Docker. Docker containers are designed to run on everything from physical computers to virtual machines, bare-metal servers, OpenStack cloud clusters, public instances and more.

8. What is Docker?
 Docker is a tool designed to make it easier to create, deploy, and run applications by using containers. Containers allow a developer to package up an application with all of the parts it needs, such as libraries and other dependencies, and ship it all out as one package. By doing so, thanks to the container, the developer can rest assured that the application will run on any other Linux machine regardless of any customized settings that machine might have that could differ from the machine used for writing and testing the code.
 In a way, Docker is a bit like a virtual machine. But unlike a virtual machine, rather than creating a whole virtual operating system, Docker allows applications to use the same Linux kernel as the system that they're running on and only requires applications be shipped with things not already running on the host computer. This gives a significant performance boost and reduces the size of the application.

9. what is container orchestration?
Container orchestration is all about managing the lifecycles of containers, especially in large, dynamic environments. Software teams use container orchestration to control and automate many tasks:
        Provisioning and deployment of containers
       Redundancy and availability of containers
       Scaling up or removing containers to spread application load evenly across host infrastructure
       Movement of containers from one host to another if there is a shortage of resources in a host, or if a host dies
       Allocation of resources between containers
       External exposure of services running in a container with the outside world
       Load balancing of service discovery between containers
       Health monitoring of containers and hosts
       Configuration of an application in relation to the containers running it
 
10.Explain the Netflix Components.
Service Discovery Server: Netflix Eureka
Edge Server: Netflix Zuul.
Central configuration server: Spring cloud config server.
Dynamic routing and load balancer: Netflix ribbon.
Oauth 2.0 protected Apis: Spring cloud + spring security OAuth 2

Monitoring Netflix Hystrix dashboard and turbine.


What is Feign Client and How to use it?


Feign client what does it mean and what it exactly does and compared to the rest template how does it outstands itself and make flexible for the developers will be seen in this tutorial.


Feign is a declarative web service client. It makes writing web service clients easier. To use Feign create an interface and annotate it. It has pluggable annotation support including Feign annotations and JAX-RS annotations.Feign also supports pluggable encoders and decoders. Spring Cloud adds support for Spring MVC annotations and for using the same HttpMessageConverters used by default in Spring Web. Spring Cloud integrates Ribbon and Eureka to provide a load-balanced HTTP client when using Feign.


This Feign client internally creates the rest template and call the corresponding service.
One of the advantages of using Feign over RestTemplate is that, we do not need to write any implementation to call the other services. So there is no need to write any unit test as there is no code to test in the first place. However, it is advised that we write Integration tests.


There are also certain advantages such as Feign integrates with Ribbon and Eureka Automatically. Feign provides a very easy way to call RESTful services. we can also use Eureka Client ID instead of the URL and then URLs are not hardcoded.


We can see step by step procedure of calling the rest service using the feign client.
1. Download the Spring war project from the https://start.spring.io/
2. Add the following dependency.

<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
<version>2.0.0.RELEASE</version>
</dependency>

3. Create an Interface and add the methods need to be invoked.
EmployeeClient.java

package com.example.demo;
import java.util.List;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@FeignClient(value="employees",url = "http://localhost:7010/employees/")

public interface EmployeeClient {

@RequestMapping(method = RequestMethod.GET, value = "/all")
Employees getEmployees();

@GetMapping(value = "/employee/{id}")
List<Employee> getIdEmployees(@PathVariable(name= "id") Integer empId);

}

Here @FeignClient(value="employees",url = "http://localhost:7010/employees/")
Value is the logical name of the application which needs to be invoked. You can also mention the url in some cases this is the base url of the application.
getIdEmployees(Interger empId) is the method defined in my service class. @GetMapping is the path of the service in the class. Once this done next steps is to enable the Feign Client and call it through the controller.


4. DemoApplication.java
package com.example.demo;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;


@SpringBootApplication
@EnableFeignClients
@RequestMapping(path = "/feign")
public class DemoApplication {

@Autowired
private EmployeeClient employeeDao;

public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}

@GetMapping(path = "/", produces = "application/json")
public Employees getEmployees() {
System.out.println("Got**********"+employeeDao.getEmployees());
return employeeDao.getEmployees();
}

@GetMapping(path = "/employee/{id}", produces = "application/json")
public ResponseEntity<List<Employee>> getIdEmployees(@PathVariable Integer id) {
System.out.println("Got Id" + id);
List<Employee> employees = employeeDao.getIdEmployees(id);
System.out.println("Got Response as "+ employees);
return new ResponseEntity<List<Employee>>(employees, HttpStatus.OK);
}

}


Here with the annotation @EnableFeignClients we have enabled the feign client. Inject the Interface here and call the corresponding method. You can see the getIdEmployees method above for reference.

Now in the Service Layer or Service Needs to be called.

5. EmployeeController.java

@RestController
@RequestMapping(path = "/employees")
public class EmployeeController
{
@Autowired
private EmployeeDAO employeeDao;

@GetMapping(path="/all", produces = "application/json")
public Employees getEmployees()
{
return employeeDao.getAllEmployees();
}

@GetMapping(path="/employee/{id}", produces = "application/json")
public List<Employee> getIdEmployees(@PathVariable Integer id)
{
System.out.println("Called GetIdEmployee>>>>>"+id);
return employeeDao.getEmployeeId(id);
}
}



6. EmployeeDAO.java


@Repository
public class EmployeeDAO {
private static Employees list = new Employees();

static {
list.getEmployeeList().add(new Employee(1, "Syed", "rizwan", "syed@gmail.com"));
list.getEmployeeList().add(new Employee(2, "Ghouse", "basha", "ghouse@gmail.com"));
list.getEmployeeList().add(new Employee(3, "Shahin", "Kameron", "shahin@gmail.com"));
}

public Employees getAllEmployees() {
return list;
}

public void addEmployee(Employee employee) {
list.getEmployeeList().add(employee);
}

public List<Employee> getEmployeeId(int id) {
System.out.println("********* Id" + id);
Map<Integer, List<Employee>> idMap = list.getEmployeeList().stream().filter(emp -> emp.getId().equals(id))
.collect(Collectors.groupingBy(Employee::getId));
System.out.println("********* Map" + idMap);
return idMap.get(id);

}
}



Make Sure you create this employee pojo in both applications. Happy Learning !!! 

Sunday, 28 July 2019

Configuring Edge (proxy) server – Zuul

Zuul is an edge server or proxy server, and serves the requests of external applications such as UI client, Android/iOS app, or any third-party consumer of APIs offered by the product or service. Conceptually, it is a door to external applications.

Zuul allows dynamic routing and monitoring of requests. It also performs security operations like authentication. It can identify authentication requirements for each resource and reject any request that does not satisfy them.

In this Tutorial You’ll write a simple microservice application and then build a reverse proxy application that uses Netflix Zuul to forward requests to the service application. You’ll also see how to use Zuul to filter requests made through the proxy service.

Here I have created two projects Profile Service and Zuul Gateway. I am going to make all the changes to the Zuul Gateway Project. I can access any Profile Service using their port also using this proxy.

I will show here only the ZuulGateway Setup. InProfile Service just configure any sample service.

Gradle dependencies.

buildscript {
ext {
springBootVersion = '1.4.0.RELEASE'
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
}
}

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'idea'
apply plugin: 'spring-boot'
apply plugin: 'io.spring.dependency-management'

jar {
baseName = 'gateway'
version = '0.0.1-SNAPSHOT'
}
sourceCompatibility = 1.8
targetCompatibility = 1.8

repositories {
mavenCentral()
}


dependencies {
compile('org.springframework.cloud:spring-cloud-starter-zuul')
compile('org.springframework.boot:spring-boot-starter-web')
testCompile('org.springframework.boot:spring-boot-starter-test')
}

dependencyManagement {
imports {
mavenBom "org.springframework.cloud:spring-cloud-dependencies:Brixton.SR5"
}
}


eclipse {
classpath {
containers.remove('org.eclipse.jdt.launching.JRE_CONTAINER')
containers 'org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8'
}
}

Create a Filter class.

package com.example.sayhello;

import javax.servlet.http.HttpServletRequest;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.ZuulFilter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SimpleFilter extends ZuulFilter {

  private static Logger log = LoggerFactory.getLogger(SimpleFilter.class);

  @Override
  public String filterType() {
    return "pre";
  }

  @Override
  public int filterOrder() {
    return 1;
  }

  @Override
  public boolean shouldFilter() {
    return true;
  }

  @Override
  public Object run() {
    RequestContext ctx = RequestContext.getCurrentContext();
    HttpServletRequest request = ctx.getRequest();

    log.info(String.format("%s request to %s", request.getMethod(), request.getRequestURL().toString()));

    return null;
  }

}

Inject the Filter class in the Main class. Also Enable Zuul Proxy.

package com.example.sayhello;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.zuul.EnableZuulProxy;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
@RestController
@EnableZuulProxy
public class SayHelloApplication {
@Bean
  public SimpleFilter simpleFilter() {
    return new SimpleFilter();
  }

public static void main(String[] args) {
SpringApplication.run(SayHelloApplication.class, args);
}

}

Configuration.

Below are the configuration in the ZuulGateway.

/ZuulGateway/src/main/resources/application.properties

zuul.routes.profileService.url=http://localhost:8080

ribbon.eureka.enabled=false

server.port=8093

spring.application.name=ZuulGateway

Here profileservice is the name of the spring boot application. and Url is the Url of the Project profileService.

Now I can access the Profile service using the Following Url.

Original Url: http://localhost:8080/user/name/sarath

Proxy Url: http://localhost:8093/profileService/user/name/sarath

We get the Following log information from the filter class.

2019-07-28 19:08:53.410  INFO 20184 --- [io-8093-exec-10] com.example.sayhello.SimpleFilter        : GET request to http://localhost:8093/profileService/user/name/sarath

Happy Learning !!!! 

Circuit breaker – Hystrix

Hystrix tool is for circuit breaker operations, that is, latency and fault tolerance.Therefore, Hystrix stops cascading failures. Hystrix performs the real-time operations for monitoring the services and property changes, and supports concurrency.

Gradle Dependency.

buildscript {
ext {
springBootVersion = '2.1.6.RELEASE'
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
}
}

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'

bootJar {
baseName = 'user'
version = '0.0.1-SNAPSHOT'
}
sourceCompatibility = 1.8
targetCompatibility = 1.8

repositories {
mavenCentral()
}


dependencies {
compile('org.springframework.cloud:spring-cloud-starter-netflix-hystrix')
compile('org.springframework.cloud:spring-cloud-starter-netflix-ribbon')
compile('org.springframework.boot:spring-boot-starter-web')
testCompile('org.springframework.boot:spring-boot-starter-test')
}

dependencyManagement {
imports {
mavenBom "org.springframework.cloud:spring-cloud-dependencies:Finchley.SR2"
}
}

eclipse {
classpath {
containers.remove('org.eclipse.jdt.launching.JRE_CONTAINER')
containers 'org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8'
}
}

Main Class:

package com.example.sayhello;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@SpringBootApplication
@RestController
@EnableCircuitBreaker
public class SayHelloApplication {
@Bean
  RestTemplate restTemplate(){
    return new RestTemplate();
  }

  @Autowired
  RestTemplate restTemplate;
  
  @Autowired
  ProfileService profileService;
@Bean
public ProfileService getBookService() {
return new  ProfileService(restTemplate);
}

private static Logger log = LoggerFactory.getLogger(SayHelloApplication.class);

@RequestMapping("/callService")
  public Object invoke() {
    Object obj = getBookService().readProfileList();
    return obj;
  }

public static void main(String[] args) {
SpringApplication.run(SayHelloApplication.class, args);
}

}

Service Class:

package com.example.sayhello;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.net.URI;

@Service
public class ProfileService {

  private final RestTemplate restTemplate;

  public ProfileService(RestTemplate rest) {
    this.restTemplate = rest;
  }

  @HystrixCommand(fallbackMethod = "adminProfile")
  public String readProfileList() {
    URI uri = URI.create("http://localhost:8180/user/name/sarath");
    return this.restTemplate.getForObject(uri, String.class);
  }

  public String adminProfile() {
  URI uri = URI.create("http://localhost:8080/user/name/Syed");
    return this.restTemplate.getForObject(uri, String.class);
  }

}

From the above class if the localhost:8180 is not accessible then It will access the localhost:8080. 
Thanks God We end up in seeing the alternate when the service is down.

Client Side Load Balancing with Ribbon and Spring Cloud

Microservice architecture is of no use if there is no inter-process or service communication. The Ribbon application provides this feature. Ribbon works with Eureka for load balancing and with Hystrix for fault tolerance or circuit breaker operations.

Ribbon also supports TCP and UDP protocols, apart from HTTP. It provides these protocol supports in both asynchronous and reactive models. It also provides the caching and batching capabilities.

In this Tutorial We are going to see the client side loadbalacing with ribbon and spring cloud. In this I have three projects as say-hello and other project named profileService, and profileService2 which is running with the profile related services. Now we will access this profileServie and return the response.

Follow the below steps.

1.Create a project named 'say-hello'.
2.Add the gradle dependencies.

buildscript {
ext {
springBootVersion = '2.1.6.RELEASE'
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
}
}

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'

bootJar {
baseName = 'user'
version = '0.0.1-SNAPSHOT'
}
sourceCompatibility = 1.8
targetCompatibility = 1.8

repositories {
mavenCentral()
}


dependencies {
compile('org.springframework.cloud:spring-cloud-starter-netflix-ribbon')
compile('org.springframework.boot:spring-boot-starter-web')
testCompile('org.springframework.boot:spring-boot-starter-test')
}

dependencyManagement {
imports {
mavenBom "org.springframework.cloud:spring-cloud-dependencies:Finchley.SR2"
}
}

eclipse {
classpath {
containers.remove('org.eclipse.jdt.launching.JRE_CONTAINER')
containers 'org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8'
}
}

3. Create a main class with the Following content.

package com.example.sayhello;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.netflix.ribbon.RibbonClient;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@SpringBootApplication
@RestController
@RibbonClient(name = "say-hello",configuration = RibbonConfiguration.class)
public class SayHelloApplication {
@Bean
@LoadBalanced
  RestTemplate restTemplate(){
    return new RestTemplate();
  }

  @Autowired
  RestTemplate restTemplate;
private static Logger log = LoggerFactory.getLogger(SayHelloApplication.class);

@RequestMapping("/callService")
  public Object invoke() {
    Object obj = this.restTemplate.getForObject("http://say-hello/user/name/sarath", String.class);
    return obj;
  }

public static void main(String[] args) {
SpringApplication.run(SayHelloApplication.class, args);
}

}

4.Now we have created a service which Invokes my service and returns the Object. Next is to define the Configuration.

/say-hello/src/main/resources/application.yml

spring:
  application:
    name: say-hello

server:
  port: 8091
  
say-hello:
  ribbon:
    eureka:
      enabled: false
    listOfServers: localhost:8080,localhost:8180
    ServerListRefreshInterval: 15000
5.We should also define the ribbon configuration class.

RibbonConfiguration.class

package com.example.sayhello;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;

import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.IPing;
import com.netflix.loadbalancer.PingUrl;

public class RibbonConfiguration {

  @Autowired
  IClientConfig ribbonClientConfig;

  @Bean
  public IPing ribbonPing(IClientConfig config) {
    return new PingUrl();
  }

 }


Testing the Url.

When you call the http://localhost:8091/callService

It responds from 8080 and 8081 service respectively.

Congratulations we have implemented the Loadbalancer for the Application. The Implementation may differs calling directly or from another api.

Happy Learning !!!

Service Registry in MicroServices

The Service registry is a database populated with the information in how to dispatch requests to microservices instances.

In this tutorial we are using the Eureka Server is used for service discovery and registration.

For Setting up Follow the Below Steps:

Eureka Server.

For Configuring the server side follow the below steps.

1.Create a project named Discovery Server.
2.Add the Gradle dependencies.

Below is my File. /DiscoveryServer/build.gradle

plugins {
id 'org.springframework.boot' version '2.1.3.RELEASE'
id 'java'
}

apply plugin: 'io.spring.dependency-management'

group = 'com.searchendeca.ecommerce'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'

repositories {
mavenCentral()
}

ext {
set('springCloudVersion', 'Greenwich.SR1')
}

dependencies {
implementation 'org.springframework.cloud:spring-cloud-starter-netflix-eureka-server'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

dependencyManagement {
imports {
mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}"
}
}

3. Configurations related to the Eureka server.

Below is the file.

/DiscoveryServer/src/main/resources/application.properties

server.port=8761

eureka.client.register-with-eureka=false
eureka.client.fetch-registry=false

//When the registry starts up it will complain that there are no replica nodes for the registry to //connect to disable the relevant logging.
logging.level.com.netflix.eureka=OFF
logging.level.com.netflix.discovery=OFF

4.Main Class.

You’ll first need a Eureka Service registry. You can use Spring Cloud’s @EnableEurekaServer to stand up a registry that other applications can talk to. This is a regular Spring Boot application with one annotation added to enable the service registry.

package com.searchendeca.ecommerce.DiscoveryServer;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;

@SpringBootApplication
@EnableEurekaServer
public class DiscoveryServerApplication {

public static void main(String[] args) {
SpringApplication.run(DiscoveryServerApplication.class, args);
}

}


Now Server side configuration are done and now its time to configure the client service. Its not necessary to be a separate project, instead your custom project where you have hosted your services.

Client Side.

For Configuring the client side follow the below steps.

1. My Project Named ProfileService
2.Add Gradle Dependencies.

Below is my File /ProfileService/build.gradle

plugins {
id 'org.springframework.boot' version '2.1.3.RELEASE'
id 'java'
}

apply plugin: 'io.spring.dependency-management'

group = 'com.searchendeca.ecommerce'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'

repositories {
mavenCentral()
}

ext {
set('springCloudVersion', 'Greenwich.SR1')
}

dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.cloud:spring-cloud-starter-netflix-eureka-client'
compile("org.springframework.boot:spring-boot-starter-data-mongodb")
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

dependencyManagement {
imports {
mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}"
}
}

3.Below is my configuration.

/ProfileService/src/main/resources/application.properties

spring.application.name=profileService

4.Below is the Main class where the client identifies.

/ProfileService/src/main/java/com/searchendeca/user/ProfileServiceApplication.java

package com.searchendeca.user;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

@SpringBootApplication
@EnableDiscoveryClient

public class ProfileServiceApplication {

public static void main(String[] args) {
SpringApplication.run(ProfileServiceApplication.class, args);
}

}
Once this is setup your client service is identified in the eureka server.

Testing the application.



Access the Eureka server on http://localhost:8761/ you will see the service registered there.

Now Congratulations you have setup the discovery server and registered in it.



Happy Learning !!!