hystrix

hystrix fuse : fuse only works on the service call side, just change the logic of the consumer side
1) fuse switch mutual conversion
a. The health status of the service = the number of failed requests / the total number of requests.
b. The fuse switch is turned from off to on State transitions are determined by comparing the current service health with a set threshold
b1. When closed, requests are allowed to go through the circuit breaker. If the current health is above the set threshold, the switch remains closed. If the current health is below the set threshold Threshold, the switch is switched to the open state
b2. In the open state, after a period of time, the fuse will automatically enter the half-open state. At this time, the fuse only allows one request to pass through. When the request is successfully called, the fuse returns to the closed state . If the request fails, the circuit breaker remains open, and subsequent requests are prohibited from passing through
c. Ensure that the service caller returns the result quickly when calling an abnormal service, avoiding a large number of synchronous waiting
d. Continue to detect after a period of time Request the execution result, provide the possibility to restore the service call

2) Parameter setting
a.circuitBreaker.requestVolumeThreshold //The size of the sliding window, the default is 20
b.circuitBreaker.sleepWindowInMilliseconds //It takes too long, the fuse will check whether it is turned on again, the default is 5000, i.e. 5s
c.circuitBreaker.errorThresholdPercentage //Error rate, default 50%
When 50% of 20 requests fail, the circuit breaker will be turned on, and calling this service again at this time will return failure directly. No longer call remote services. After 5s, re-detect the trigger condition to determine whether to close the fuse or continue to open it

1) pom.xml: Feign already depends on Hystrix, so there is no need to make any changes in maven configuration
2) application.yml:
    feign:
        hystrix:
            enable: true
3) Startup class
@EnableFeignClients //Enable feigin annotation
@EnableCircuitBreaker // Open Hystrix
@EnableDiscoveryClient //Open the registry
@SpringBootApplication //spring-boot starts
public class Application {
    @Bean
    @LoadBalanced
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }

    public static void main(String[] args) {
        SpringApplication .run(Application.class, args);
    }
}
Note: You can also use @SpringCloudApplication instead, @SpringCloudApplication includes the following annotations: @Target({ElementType.TYPE}, @Retention(RetentionPolicy.RUNTIME), @Documented, @Inherited, @SpringBootApplication, @EnableDiscoveryClient, @EnableCircuitBreaker
4) serviceImplement layer
@ HystrixCommand(fallbackMethod = "findOrderFallback", commandProperties = {            
    @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "1000")//timeoutInMilliseconds When using thread isolation, call timeout time
})
public String findOrder(Long userId,String orderNo) throws InterruptedException {
    Random random = new Random();
    sleepRandom = random.nextInt(2000);
    System.out.println("sleepRandom="+sleepRandom);
    Thread.sleep(sleepRandom);
    ConsumerBeehiveUser user = findById(userId);
    if (user != null) {
        return user.getUsername() + " order" + orderNo + " found! sleepRandom="+sleepRandom;
    }
    return "user does not exist! sleepRandom=" +sleepRandom;
}
public String findOrderFallback(Long userId, String orderNo) {
    return "Order search failed! sleepRandom="+sleepRandom;
}
Parameter description:
a. Snapshot time window: To determine whether to open the circuit breaker, some request and error data need to be counted. The statistical time range is the snapshot time window, which defaults to the latest 10 seconds.
b. The lower limit of the total number of requests: within the snapshot time window, the lower limit of the total number of requests must be met to be eligible for circuit breaker. The default is 20, which means that within 10 seconds, if the hystrix command is called less than 20 times at this time, the circuit breaker will not open even if all requests time out or fail for other reasons.
c. Lower limit of error percentage: When the total number of requests exceeds the lower limit within the snapshot time window, such as 30 calls, if 16 of the 30 calls have a timeout exception, that is, the error percentage exceeds 50%, Under the default setting of 50% lower limit, the circuit breaker will be opened at this time.
Fallback is downgrade processing

2. Isolation :
1) Startup class:
    @SpringBootApplication
    @EnableDiscoveryClient //Enable eureka service
    @EnableFeignClients //Enable feigin annotation
    @EnableCircuitBreaker //Enable Hystrix @EnableCircuitBreaker or @EnableHystrix
    @EnableHystrixDashboard //Enable dashboard graphic monitoring
    public class ConsumerBeehiveApplication {
            @Bean
            @LoadBalanced
            public RestTemplate restTemplate() {
                / /Method for calling "provider"
                return new RestTemplate();
            }

            public static void main(String[] args) {
                SpringApplication.run(ConsumerBeehiveApplication.class, args);
            }
    }
2) serviceimplement:
@HystrixCommand(fallbackMethod = "testCircuitBreakerFallback", commandProperties = {
    @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "50")//errorThresholdPercentage circuit breaker error request percentage
})
public String testCircuitBreaker(int id) {
    if(id % 2 == 0 && id < 10) { // return directly
        return "consumer testCircuitBreaker "+id;
    } else { // infinite loop simulation timeout
        int j = 0;
        while (true) {
              j++;
        }
    }
}
public String testCircuitBreakerFallback (int id) {
    String template = restTemplate.getForObject("http://provider-user/user/testCircuitBreaker/"+id, String.class);
    return "fallback:"+template;
}




    Construct the Command object of Hystrix and call the execution method.
    Hystrix checks whether the circuit breaker switch of the current service is turned on. If it is turned on, it executes the getFallback method of the downgraded service.
    If the circuit breaker switch is turned off, Hystrix checks whether the thread pool of the current service can receive new If the request exceeds the thread pool is full, the downgrade service getFallback method is executed.
    If the thread pool accepts the request, Hystrix starts to execute the service to call the specific logical run method.
    If the service fails to execute, the downgrade service getFallback method is executed, and the execution result is reported Metrics updates the service health status.
    If the service execution times out, the downgrade service getFallback method is executed, and the execution result is reported to Metrics to update the service health status.
    If the service execution is successful, the normal result is returned.
    If the service downgrade method getFallback is successfully executed, the downgrade result is returned. .If
    the service downgrade method getFallback fails to execute, an exception will be thrown.
    
Configuration parameter description
1.HystrixCommandProperties: HystrixProperty type
1) Metrics
a.metricsRollingStatisticalWindowInMilliseconds: Statistics rolling time window, default: 5000 milliseconds (taken from circuitBreakerSleepWindowInMilliseconds)
b.metricsRollingStatisticalWindowBuckets: Statistics The number of Buckets in the window, default: 10, one Buckets per second
c.metrics.rollingPercentile.enabled: Whether to enable monitoring statistics function, default: true
d.metrics.rollingStats.timeInMilliseconds:
e.metrics.rollingStats.numBuckets:
f.metrics.rollingPercentile.timeInMilliseconds:
h.metrics.rollingPercentile.numBuckets:
i .metrics.rollingPercentile.bucketSize:
g.metrics.healthSnapshot.intervalInMilliseconds
h.circuitBreaker.requestVolumeThreshold: Threshold for circuit breaker request, the threshold for whether the circuit breaker is turned on during the entire statistical time, the default is 20. That is, at least 20 requests are made within the metricsRollingStatisticalWindowInMilliseconds (default 10s), the fuse
will
work After that, it will enter the half-open state, put down a request and try again, if the request is successful, turn off the fuse, otherwise continue to wait for a fuse time window
b.circuitBreaker.enabled: circuit breaker switch, whether to enable the fuse, the default is true. Start
c.circuitBreaker.errorThresholdPercentage: The percentage of circuit breaker error requests, default: 50%. When the error rate exceeds 50%, the fuse will start
d.circuitBreaker.forceOpen: the circuit breaker is forced to open, whether to force the fuse to block all requests, default: false, not open. When set to true, all requests will be rejected directly to fallback
e.circuitBreaker.forceClosed: the circuit breaker is forced to close, whether to allow the circuit breaker to ignore errors, default false, not open
3) Execution
a.execution.isolation.semaphore.maxConcurrentRequests : When using semaphore isolation, the maximum number of concurrent command calls, default: 10
b.execution.isolation.strategy: Use command call isolation mode, default: use thread isolation, ExecutionIsolationStrategy.THREAD
c.execution.isolation.thread.timeoutInMilliseconds: When thread isolation is used, the call timeout time, default: 1 second
d.executionIsolationThreadPoolKeyOverride: the key of the thread pool, which is used to determine which thread pool the command is executed in
e.execution.isolation.thread.interruptOnTimeout: whether to execute the command when using thread isolation The timeout thread calls interrupt (Thread.interrupt()) operation. Default: true
f.execution.timeout.enabled:
4)Fallback
a.fallback.isolation.semaphore.maxConcurrentRequests: When using semaphore isolation, the command fallback (downgrade) calls the maximum number of concurrent calls, default: 10
b.fallback.enabled: Whether to enable fallback degradation strategy Default: true
5) Request Context
a. requestLogEnabled: Whether to enable the request log, default: true
b.requestCacheEnabled: Whether to enable the request cache, default: true
2.HystrixCollapserProperties: HystrixProperty type
1) maxRequestsInBatch: Request merge is the maximum number of requests allowed, default: Integer.MAX_VALUE
2) timerDelayInMilliseconds: The delay time of each command in the batch process, default
:
10
milliseconds . Recommended value: 99.5% of the average response time at the peak of the request + reserve some upwards.
2) maxQueueSize: Configure the thread value to wait for the queue length, the default value: -1, the recommended value: -1, which means that it will not wait and directly reject, test Indicates that the thread pool is most efficient using the direct decision strategy + a non-retracting thread pool of a suitable size. Therefore, it is not recommended to modify this value. When using a non-retracting thread pool, the queueSizeRejectionThreshold, keepAliveTimeMinutes parameters are invalid
3) queueSizeRejectionThreshold: Queue size rejection threshold
4) keepAliveTimeMinutes
5) metrics.rollingStats.timeInMilliseconds
6) metrics.rollingStats.numBuckets

Guess you like

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