0502 - Hystrix Protection Application - Introduction, Usage, Health Metrics and More

I. Overview

  See the address: https://cloud.spring.io/spring-cloud-static/Edgware.SR3/single/spring-cloud.html#_circuit_breaker_hystrix_clients

  源码wiki:https://github.com/Netflix/Hystrix/wiki

  Netflix created a library called Hystrix that implements the circuit breaker pattern. In a microservice architecture, there are often multiple layers of service calls.

  Service failures in lower-level services can lead to cascading failures down to the user. When calls to a particular service are greater than CurrBurnReal.RealStestMultRESHOLD (default: 20 requests) and the failure rate is greater than the TraceBurror.Error threshold percentage (default: 50%) in a rolling window defined by MultICC.LoLink StutsTimeMimLimeDS (default: 10 seconds) , the circuit is disconnected and no call is made. Developers can provide fallbacks in the event of errors and open circuits.

  

  Open circuits prevent cascading failures and allow services to recover themselves. The fallback can be another protected call to Hystrix, static data or a null value. Fallbacks may be chains, so the first fallback causes other business calls to fall back to static data instead.

2. Use

2.1. Introduction to hystrix-javanica

  Source address: https://github.com/Netflix/Hystrix/tree/master/hystrix-contrib/hystrix-javanica

  The Java language has great advantages over other languages ​​like reflection and annotations. All modern frameworks like Spring, Hibernate, myBatis, etc. strive to maximize these advantages. The idea of ​​introducing annotations in Hystrix is ​​the obvious solution for improvement. Using Hystrix currently involves writing a lot of code, which is a barrier to rapid development. You probably spend a lot of time writing Hystrix commands. By introducing support annotations, the idea of ​​the Javanica project makes it easier to use Hystrix.

  Simplified Hystrix usage

2.2, use

  @HystrixCommand is provided by a Netflix contrib library called "javanica". Spring Cloud will automatically wrap Spring beans with this annotation in proxies that connect to Hystrix circuit breakers. A circuit breaker calculates when to open and close a circuit, and what to do in the event of a fault.

  To configure @HystrixCommand you can use commandProperties property with @HystrixProperty annotation list

 pom quote

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
        </dependency>

Add the following annotations to the startup class

@EnableCircuitBreaker

Add annotations and fallback methods to the calling method

@Component
public class StoreIntegration {

    @HystrixCommand(fallbackMethod = "defaultStores")
    public Object getStores(Map<String, Object> parameters) {
        //do stuff that might fail
    }

    public Object defaultStores(Map<String, Object> parameters) {
        return /* something useful */;
    }
}

important point:

1. fallbackMethod must be a defined method

2. The return value of the defaultStores method parameter is  the same as that marked by the annotation HystrixCommand

3. After a problem occurs, it will be processed by defaultStores .

3. Other

3.1. Propagating the security context or using Spring Scopes

  If you want some thread-local context to propagate to @HystrixCommand, the default declaration won't work because it executes the command in the thread pool (in case of timeout). You can switch Hystrix to use the same thread as the caller using some configuration, or request it to use a different "isolation strategy" directly in the annotation.

  See address: https://github.com/Netflix/Hystrix/wiki/Configuration#command-properties

  execution.isolation.strategy: This property indicates the isolation strategy for HystrixCommand.run() execution, one of two choices:

    THREAD - it executes on a separate thread, concurrent requests are limited by the number of threads in the thread pool

    SEMAPHORE - it executes on the calling thread, concurrent requests are limited by the signal count

  The default and recommended setting is to run HystrixCommands with thread isolation (THREAD) and HystrixObservableCommands with semaphore isolation (SEMAPHORE).

  Use the corresponding method to increase

@HystrixCommand(fallbackMethod = "findByIdFallback", commandProperties = @HystrixProperty(name = "execution.isolation.strategy", value = "SEMAPHORE"))

  The same applies if you use @SessionScope or @RequestScope. You'll know when you need to do this because a runtime exception indicates that the context in scope could not be found.

  [1.2 Start] You can also choose to set the hystrix.shareSecurityContext property to true. Doing so automatically configures a Hystrix concurrency policy plugin hook that can transfer the SecurityContext from the main thread to the hook used by Hystrix commands. Hystrix does not allow multiple hystrix concurrency strategies to be registered, so by declaring your own HystrixConcurrencyStrategy as a Spring bean, you can use the extension mechanism. Spring Cloud will look for your implementation in the Spring context and wrap it in its own plugin. [Generally, there is an abnormality, and it needs to be configured when there is a problem]

  See articles: https://github.com/spring-cloud/spring-cloud-netflix/issues/1330 , https://github.com/spring-cloud/spring-cloud-netflix/issues/1336

3.1.1、Scope 

 

  Scope describes how the Spring container creates a new Bean instance. Spring's Scope has the following types, which are implemented through the @Scope annotation.

  (1) Singleton: There is only one instance of Bean in a Spring container. This is the default configuration of Spring, and all containers share one instance.

  (2) Prototype: A new Bean instance is created each time it is called.

  (3) Request: In the Web project, create a new Bean instance for each http request.

  (4) Session: In the Web project, create a new Bean instance for each http session.

  (5) GlobalSession: This is only useful in portal applications. Create a new Bean instance for each global http session.

3.2. Health indicators

  The state of the connection circuit breaker is also exposed in the /health endpoint of the calling application.

  Access address: http://localhost:8761/health

can be viewed as follows

{
    "hystrix": {
        "openCircuitBreakers": [
            "StoreIntegration::getStoresByLocationLink"
        ],
        "status": "CIRCUIT_OPEN"
    },
    "status": "UP"
} 

At this point, you can disconnect the service provider and check it later

circuit breaker open

The view of health needs to be added

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>

3.3, Hystrix metric flow

  Enabling Hystrix metrics streaming includes a dependency on the spring boot enabler executor. This will expose /hystrix.stream as a management endpoint. Access specific interfaces and be able to view messages

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>

You can view it later using Dashboard

Feign also supports Hystrix

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324608718&siteId=291194637