Hystrix performs fusing downgrade

Import the required packages

<!--核心包-->
<dependency>
      <groupId>com.netflix.hystrix</groupId>
      <artifactId>hystrix-core</artifactId>
      <version>1.5.18</version>
</dependency>
<!--使用切面时需要-->
<dependency>
      <groupId>com.netflix.hystrix</groupId>
      <artifactId>hystrix-javanica</artifactId>
      <version>1.5.18</version>
</dependency>

Use method 1: Java native coding method

We can control the access interface through Hystrix native coding

Step 1: Create a command object for an interface

 /**
* 定义某个接口调用的指令类
* */
public class IhrTokenRequestCommand extends HystrixCommand<MResult<String>> {

        public IhrTokenRequestCommand(){
            //配置本接口配置参数
            super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("ThreadPoolTestGroup"))  //服务分组
                    .andCommandKey(HystrixCommandKey.Factory.asKey("testCommandKey")) 
                    .andThreadPoolKey(HystrixThreadPoolKey.Factory.asKey("ThreadPoolTest"))
                    .andCommandPropertiesDefaults(HystrixCommandProperties.Setter()
                            .withExecutionTimeoutInMilliseconds(5000)) //超时时长,默认1000
                    .andThreadPoolPropertiesDefaults(       // 配置线程池
                            HystrixThreadPoolProperties.Setter()
                                    .withCoreSize(50))  // 配置线程池里的线程数
                    .andCommandPropertiesDefaults(  // 配置熔断器
                            HystrixCommandProperties.Setter()
                                    .withCircuitBreakerEnabled(true)  //是否开启熔断机制,默认为true。
                                    .withCircuitBreakerRequestVolumeThreshold(20)  //在熔断开关闭合情况下,在进行失败率判断之前,一个采样周期内必须进行至少N个请求才能进行采样统计,目的是有足够的采样使得失败率计算正确,默认为20。
                                    .withCircuitBreakerSleepWindowInMilliseconds(3)  // 熔断后的重试时间窗口,且在该时间窗口内只允许一次重试。即在熔断开关打开后,在该时间窗口允许有一次重试,如果重试成功,则将重置Health采样统计并闭合熔断开关实现快速恢复,否则熔断开关还是打开状态,执行快速失败。
                                    .withCircuitBreakerErrorThresholdPercentage(50)  //如果在一个采样时间窗口内,失败率超过该配置,则自动打开熔断开关实现降级处理,即快速失败。默认配置下采样周期为10s,失败率为50%。
                    )
            );
        }

        //实际执行的代码,可主动抛出HystrixTimeoutException、HystrixRuntimeException等异常
        @Override
        protected MResult<String> run() throws Exception {
            return null;
        }

        //降级方法
        @Override
        protected MResult<String> getFallback() {
            MResult<String> result = new MResult<String>(ResponseCodeEnum.ERROR) ;
            return result;
        }
}

Step 2: Create an instance and execute

MResult<String>  result = new IhrTokenRequestCommand().execute();

Note that each call needs to create an instance


Usage 2: Use Spring's AOP for control

Through Spring's AOP, we can control access to the interface in a more elegant way

Step 1: Add the configuration of the required aspect

Add the following configuration in Spring's configuration file

<aop:aspectj-autoproxy/>
 <bean id="hystrixAspect" class="com.netflix.hystrix.contrib.javanica.aop.aspectj.HystrixCommandAspect"></bean>

It can also be configured through JavaConfig

@Configuration
public class HystrixAspectConfiguration {
    @Bean
    public HystrixCommandAspect hystrixAspect() {
        return new HystrixCommandAspect();
    }
}

Step 2: Add comments to the method

public class HystrixResourceApi {

    @HystrixCommand(commandProperties = {
            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "50")
    },fallbackMethod = "fallbackForGetUser")
    public String getUserById(String id) {
        throw new RuntimeException("getUserById command failed");
    }
    /**
     * fallback 方法,原方法被降级的时候调用
     * */
    String fallbackForGetUser(String id) {
        return "unknown";
    }
}

Then, use the method normally through dependency injection where needed.


HystrixCommandProperties configuration instructions

parameter Description
withFallbackEnabled Whether to enable downgrade processing, if it is enabled, call getFallback to perform downgrade processing when timeout or exception occurs. It is enabled by default.
withFallbackIsolationSemaphoreMaxConcurrentRequests The semaphore configuration of the fallback method is to configure the semaphore of the concurrent request of the getFallback method. If the request exceeds the concurrent semaphore limit, no more attempts are made to call the getFallback method, but it fails quickly. The default semaphore is 10.
withExecutionIsolationThreadInterruptOnFutureCancel When the isolation strategy is THREAD, whether to perform interrupt processing when the execution thread execution times out, that is, Future#cancel(true) processing, the default is false
withExecutionIsolationThreadInterruptOnTimeout When the isolation strategy is THREAD, whether to perform interrupt processing when the execution thread execution times out, the default is true.
withExecutionTimeoutEnabled Whether to enable the execution timeout mechanism, the default is true
withExecutionTimeoutInMilliseconds The execution timeout time, the default is 1000 milliseconds. If the command is thread isolation and executionIsolationThreadInterruptOnTimeout=true is configured, the execution thread will execute interrupt processing. If the command is semaphore isolation, then terminate operation, because semaphore isolation and the main thread are executed in the same thread, it will not interrupt the thread processing, so it is necessary to decide whether to use semaphore isolation according to the actual situation, especially involving network access Case.
withCircuitBreakerEnabled Whether to open the fuse mechanism, the default is true.
withCircuitBreakerForceClosed Whether to forcibly close the fuse switch, if the fuse switch is forcibly closed, the request will not be downgraded. In some special scenarios, the switch can be dynamically configured, and the default is false.
withCircuitBreakerForceOpen Whether to force the fuse switch to be opened, if the fuse switch is forcibly opened, the request is forced to downgrade to call getFallback processing. The switch can be opened through dynamic configuration to achieve some special requirements, the default is false.
withCircuitBreakerErrorThresholdPercentage If within a sampling time window, the failure rate exceeds this configuration, the fuse switch is automatically turned on to achieve degradation processing, that is, rapid failure. In the default configuration, the sampling period is 10s, and the failure rate is 50%.
withCircuitBreakerRequestVolumeThreshold In the case of fusing and closing, before the failure rate is judged, at least N requests must be made in a sampling period to perform sampling statistics. The purpose is to have enough sampling to make the failure rate calculation correct. The default is 20.
withCircuitBreakerSleepWindowInMilliseconds The retry time window after fusing, and only one retry is allowed in this time window. That is, after the fuse switch is opened, one retry is allowed in this time window. If the retry is successful, the Health sampling statistics will be reset and the fuse switch will be closed to achieve rapid recovery. Otherwise, the fuse switch is still open and the execution fails quickly. After fusing, getFallback will be downgraded to be processed (fallbackEnabled=true), and you can judge whether it is fused by the following method of Command.
isCircuitBreakerOpen Whether the fuse switch is opened, pass "circuitBreakerForceOpen().get() (!circuitBreakerForceClosed().get() && circuitBreaker.isOpen())”判断。
isResponseShortCircuited isCircuitBreakerOpen=true, and return true when getFallback is called.

For more information, please refer to: https://www.sohu.com/a/134459931_494947

Guess you like

Origin blog.51cto.com/dengshuangfu/2544597