Quick Refresh : Micro services : Declarative REST Client: Feign, Client Side Load Balancer: Ribbon, Service Discovery: Eureka Server, Eureka Client, Circuit Breaker: Hystrix, Hystrix Dashboard
What Is a Feign Client?
Netflix provides Feign as an abstraction over REST-based calls, by which microservices can communicate with each other, but developers don't have to bother about REST internal details.
Why We Use Feign Client
Earlier When one micro service communicated with another micro service, we programmatically constructed the URL of the dependent microservice,then called the service using RestTemplate, so we need to be aware of the RestTemplate API to communicate with other microservices, which is certainly not part of our business logic.
The question is, why should a developer have to know the details of a REST API? Microservice developers only concentrate on business logic, so Spring addresses this issues and comes with Feign Client, which works on the declarative principle. We have to create an interface/contract, then Spring creates the original implementation on the fly, so a REST-based service call is abstracted from developers. Not only that — if you want to customize the call, like encoding your request or decoding the response in a Custom Object, you can do it with Feign in a declarative way. Feign, as a client, is an important tool for microservice developers to communicate with other microservices via Rest API.
Add the feign dependency in pom.xml
<dependency>
<groupId>org.springframework. cloud</groupId>
<artifactId>spring-cloud- starter-feign</artifactId>
</dependency>
Feign has to know which service to call beforehand. That's why we need to give a name for the interface, which is the {Service-Id} of EmployeeService. Now, Feign contacts the Eureka server with this Service Id, resolves the actual IP/hostname of the EmployeeService, and calls the URL provided in Request Mapping.
Note: When using @PathVariable for Feign Client, always use value property or it will give you the error java.lang. IllegalStateException: PathVariable annotation was empty on param 0
@FeignClient(name="
EmployeeSearch" )//Service Id of EmployeeSerach service public interface EmployeeServiceProxy {
@RequestMapping("/employee/
find/{id}") public EmployeeInfo findById(@PathVariable(value="
id") Long id);
@RequestMapping("/employee/
findall") public Collection<EmployeeInfo> findAll();
}
@RestController
public class FeignEmployeeInfoController {
@Autowired
EmployeeServiceProxy proxyService;
@RequestMapping("/dashboard/
feign/{myself}")
public EmployeeInfo findme(@PathVariable Long myself){
return proxyService.findById(myself);
}
@RequestMapping("/dashboard/
feign/peers") public Collection<EmployeeInfo> findPeers(){
return proxyService.findAll();
}
}
In the @FeignClient annotation the String value ("EmployeeSearch" above) is an arbitrary client name, which is used to create a Ribbon load balancer.
The Ribbon client above will want to discover the physical addresses for the "EmployeeSearch" service.
If your application is a Eureka client then it will resolve the service in the Eureka server's service registry.
If you don’t want to use Eureka, you can simply configure a list of servers in your external configuration.
You can also specify a URL using the url attribute (absolute value or just a hostname). The name of the bean in the application context is the fully qualified name of the interface. To specify your own alias value you can use the qualifier value of the @FeignClient annotation.
we also need to tell our project that we will use Feign client, so scan its annotation. For this, we need to add the @EnableFeignClients annotation on top of spring boot application's main class.
@EnableDiscoveryClient
@EnableFeignClients
@SpringBootApplication
public class EmployeeDashBoardServiceApplic
ation {
public static void main(String[] args) {
SpringApplication.run(
EmployeeDashBoardServiceApplic ation.class, args); }
}
Feign logging: A logger is created for each Feign client created. By default the name of the logger is the full class name of the interface used to create the Feign client. Feign logging only responds to the DEBUG level.
logging.level.project.user.
UserClient: DEBUG
==========================
Client Side Load Balancer: Ribbon
Ribbon is a client-side load balancer that gives you a lot of control over the behavior of HTTP and TCP clients. Feign already uses Ribbon.
A central concept in Ribbon is that of the named client. Each load balancer is part of an group of components that work together to contact a remote server on demand,
and the ensemble has a name that you give it as an application developer (for example, by using the @FeignClient annotation). On demand, Spring Cloud creates a new ensemble as an ApplicationContext for each named client by using RibbonClientConfiguration. This contains (amongst other things) an ILoadBalancer, a RestClient, and a ServerListFilter.
Add the ribbon dependency in pom.xml
===========
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-ribbon</ artifactId>
</dependency>
Eureka: It is the Netflix Service Discovery Server and Client.
=======================
Service Discovery: Eureka Server
How to Include Eureka Server in Project:
How to Include Eureka Server in Project:
<dependency>
<groupId>org.springframework. cloud</groupId>
<artifactId>spring-cloud- starter-netflix-eureka-server< /artifactId>
</dependency>
How to Run a Eureka Server: For creating Eureka server you need to create a spring boot application and do below steps
(1) Annotate the Spring Boot application with @EnableEurekaServer to enable this as a Eureka Server. To do so, we need to add
<artifactId>spring-cloud-
</dependency>
How to Run a Eureka Server: For creating Eureka server you need to create a spring boot application and do below steps
(1) Annotate the Spring Boot application with @EnableEurekaServer to enable this as a Eureka Server. To do so, we need to add
@SpringBootApplication@EnableEurekaServerpublic class Application {public static void main(String[] args) {new SpringApplicationBuilder(Application.class).web(true). run(args); }}
(2) Disable Eureka server's self client registration with eureka server by adding below properties in application.xmleureka.client.fetch-registry=false eureka.client.register-with-eureka=false
(3) To bind the discovery application to a specific port and name add below in application.xml
eureka.instance.hostname=localhost server.port=8761spring.application.name=DiscoveryServer
The server has a home page with a UI and HTTP API endpoints for the normal Eureka functionality under /eureka/*.High Availability, Zones and Regions
The Eureka server does not have a back end store, but the service instances in the registry all have to send heartbeats to keep their registrations up to date (so this can be done in memory). Clients also have an in-memory cache of Eureka registrations (so they do not have to go to the registry for every request to a service).
By default, every Eureka server is also a Eureka client and requires (at least one) service URL to locate a peer. If you do not provide it, the service runs and works, but it fills your logs with a lot of noise about not being able to register with the peer.
Standalone Mode
The combination of the two caches (client and server) and the heartbeats make a standalone Eureka server fairly resilient to failure, as long as there is some sort of monitor or elastic runtime (such as Cloud Foundry) keeping it alive. In standalone mode, you might prefer to switch off the client side behavior so that it does not keep trying and failing to reach its peers. The following example shows how to switch off the client-side behavior:-- =============
Eureka Client:How to configure the Eureka Client in application:
(1) Include Eureka client dependency in pom.xml
<dependency>
<groupId>org.springframework. cloud</groupId>
<artifactId>spring-cloud- starter-netflix-eureka-client< /artifactId>
</dependency>
<artifactId>spring-cloud-
</dependency>
(2)Annotate your application configuration with @EnableDiscoveryClient or (@EnableEurekaClient) you can use it to discover service instances form the Eureka Server.
@SpringBootApplication@EnableEurekaClientpublic class MyEurekaClientApplication {public static void main(String[] args) {new SpringApplicationBuilder( MyEurekaClientApplication.class). web(true).run(args); }}
(3) Registering with Eureka: As a client, it should register itself to the Eureka server. below configuration is required to locate the Eureka server
When a client registers with Eureka, it provides meta-data about itself such as host and port, health indicator URL, home page etc. The default application name (service ID), virtual host and non-secure port, taken from the Environment are spring.application.name, spring.application.name and server.port respectively. The Eureka instance is configured by eureka.instance.* configuration keys, but the defaults will be fine if you ensure that your application has a spring.application.name (this is the default for the Eureka service ID or VIP). The eureka.instance.serviceUrl.eureka.client.serviceUrl.defaultZone=http://localhost: 8761/eureka/
Eureka Server receives heartbeat messages from each instance of eureka client. If the heartbeat fails over a configurable timetable, the instance is normally removed from the registry.
=================
Circuit Breaker enterprise pattern, which is describing a strategy against failure cascading at different levels in an application
Spring Cloud Netflix Hystrix – the fault tolerance library which is used to implement the Circuit Breaker
Three things you can do when circuit break condition met -
- Throw Error
- Provide a default Response
- Provide previous cache resonse (Cache Fallback with Hystrix)
=============
=================
Circuit Breaker enterprise pattern, which is describing a strategy against failure cascading at different levels in an application
Spring Cloud Netflix Hystrix – the fault tolerance library which is used to implement the Circuit Breaker
Three things you can do when circuit break condition met -
- Throw Error
- Provide a default Response
- Provide previous cache resonse (Cache Fallback with Hystrix)
=============
Spring Cloud Netflix Hystrix
<dependency><groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-hystrix</artifactId>l </dependency>
for the Circuit Breaker to work, Hystix will scan @Component or @Service annotated classes for @HystixCommand annotated methods, implement a proxy for it and monitor its calls.
Rest Consumer Application main application class should be annotate with @EnableCircuitBreaker annotation which will scan the classpath for any compatible Circuit Breaker implementation. To use Hystrix explicitly, you have to annotate this class with @EnableHystrix.
@SpringBootApplication
@EnableCircuitBreaker
public class RestConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(
}
}
============
Hystrix Dashboard
A nice optional feature of Hystrix is the ability to monitor its status on a dashboard.
To enable it, we’ll put spring-cloud-starter-hystrix-
<dependency>
<groupId>org.springframework.
<artifactId>spring-cloud-
</dependency>
<dependency>
<groupId>org.springframework.
<artifactId>spring-boot-
</dependency>
The former needs to be enabled via annotating a @Configuration with @EnableHystrixDashboard and the latter automatically enables the required metrics within our web-application.
After we’ve done restarting the application, we’ll point a browser at http://localhost:8080/hystrix, input the metrics URL of a ‘hystrix.stream’ and begin monitoring.
Monitoring a ‘hystrix.stream’ is something fine, but if you have to watch multiple Hystrix-enabled applications, it will become inconvenient. For this purpose, Spring Cloud provides a tool called Turbine, which can aggregate streams to present in one Hystrix Dashboard.
Comments
Post a Comment