5. "springboot integrated Hystrix" built by springcloud microservice architecture

1. "springboot automatic assembly of Redis" built by springcloud microservice architecture

2. "springboot integrated nacos registration center" built by springcloud microservice architecture

3. "springboot automatic assembly ribbon" built by springcloud microservice architecture

4. "springboot integrated openFeign" built by springcloud microservice architecture

Table of contents

1. The project introduces hystirx

        1.1. The project introduces hystrix coordinate configuration

        1.2. Project startup class enable circuit breaker

2. HystrixCommand annotation

        2.1 Using HystrixCommand to implement fallback

                2.1.1 Normality test

                 2.1.2 Stop the cms service, the simulated service is unavailable

          2.2 Implement global fallback through DefaultProperties

                2.2.1 Stop to cms service, simulate test 

         2.3 Configure the fuse policy of the interface through custom parameters

 3. Open feign to integrate hystrix

        3.1 FeignClient interface implements downgrade strategy, FallbackFactory

                3.1.1 Normal service test

                 3.1.2 Stop the api service test

                3.1.3 If you continue to simulate frequent calls to the interface, a fuse will be triggered

 4. Global Hystrix configuration

5. Reference


1. The project introduces hystirx

        1.1. The project introduces hystrix coordinate configuration

<!-- hystrix 配置 版本号:2.1.3.RELEASE-->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
    <version>${spring.cloud.version}</version>
</dependency>

        1.2. Project startup class enable circuit breaker

package lilock.cn.user;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;

@SpringBootApplication(scanBasePackages = {"lilock.cn.*"})
@EnableConfigurationProperties
@EnableDiscoveryClient
@EnableFeignClients(basePackages = {"lilock.cn"})  //启用feign调用
@EnableCircuitBreaker // 启用断路器
public class UserApplication {
    public static void main(String[] args) {
        SpringApplication.run(UserApplication.class,args);
    }
}

2. HystrixCommand annotation

Hystrix provides HystrixCommand, which is used to configure Hystrix-related configurations, such as: callback method, timeout, fuse configuration, etc. To use hystrix, it must be annotated with @HystrixCommand

The configuration of hystrix in this mode is based on  the @HystrixCommand annotation configuration. We implement the configuration by adding the @HystrixCommand annotation to the method   and configuring the parameters of the annotation.

        2.1 Using HystrixCommand to implement fallback


    /**
     * 接口熔断
     * @return
     */
    @HystrixCommand(fallbackMethod = "testHystrixError")
    @GetMapping("/testHystrix")
    public String testHystrix(){
        log.info("testHystrix 接口调用 apiCmsServiceFeignClient.getHello");
        String value = apiCmsServiceFeignClient.getHello();
        return "[testHystrix] 验证断路器" + value;
    }


    public String testHystrixError(){
        log.info("{} testHystrixError 调用失败",System.currentTimeMillis());
        return "enable testHystrixError";
    }

                2.1.1 Normality test

                 2.1.2 Stop the cms service, the simulated service is unavailable

           

          2.2 Implement global fallback through DefaultProperties

Sometimes there will be multiple Hystrix methods in a class. If each method is configured similarly, a lot of code will be redundant. At this time, we can use the @DefaultProperties annotation on the class to  set  a default downgrade method for the Hystrix method of the entire class, especially Marked, downgrade to follow the specially marked method, no special mark, downgrade to the default method

@RestController
@RequestMapping(path = "/user")
@Api(value = "系统用户",tags = {"系统用户"})
@Slf4j
@DefaultProperties(defaultFallback = "defaultFallBackMethod")
public class UserController {
    
    /***
      * 模拟全局配置fallback
      */
    @HystrixCommand
    @GetMapping("/testHystrixTimeOutFallback")
    public BaseResult testHystrixTimeOutFallback(@RequestParam("time") long time){

        BaseResult<String> value = apiCmsHystrixServiceFeignClient.getHystrixTimeOut(time);
        log.info("testHystrixTimeOutFallback 接口调用 响应结果:{}",value);
        try{
            Thread.sleep(time);
        }catch (Exception e){
        }
        return value;
    }


    public BaseResult defaultFallBackMethod(){
        String errorMsg = System.currentTimeMillis() +  "defaultFallBackMethod 调用失败触发熔断";
        log.error("{}",errorMsg);
        return BaseResult.faild(errorMsg);
    }
}

                2.2.1 Stop to cms service, simulate test 

         2.3 Configure the fuse policy of the interface through custom parameters

Configure a timeout, and fallback takes the public mode


    /**
     * 模拟带参数走服务熔断
     * @return
     */
    @HystrixCommand(commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "1500")})
    @GetMapping("/testHystrixTimeDefault")
    public BaseResult testHystrixTimeDefault(long time){
        log.info("testHystrixTimeDefault 接口调用 apiCmsHystrixServiceFeignClient.testHystrixDefault");
        BaseResult<String> value = apiCmsHystrixServiceFeignClient.getHystrix();
        try{
            Thread.sleep(time);
        }catch (Exception e){
        }
        return value;
    }


  public BaseResult defaultFallBackMethod(){
        String errorMsg = System.currentTimeMillis() +  "defaultFallBackMethod 调用失败触发熔断";
        log.error("{}",errorMsg);
        return BaseResult.faild(errorMsg);
    }

The interface sleep time of 1000ms is less than the downgrade time of 1500ms, and returns normally 

 If the interface sleep time of 2000ms is longer than the downgrade time of 1500ms, a downgrade is triggered

 3. Open feign to integrate hystrix

configuration file open

feign:
  hystrix:
    enabled: true

        3.1 FeignClient interface implements downgrade strategy, FallbackFactory

The advantage of fallbackFactory is that it can be configured uniformly

Of course, @HystrixCommand can also be configured separately on the Api interface

package lilock.cn.cms.api;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import lilock.cn.cms.api.fallback.ApiCmsHystrixServiceFeignClientFallbackFactory;
import lilock.cn.common.resp.BaseResult;
import lilock.cn.common.ribbon.config.FeignConfig;
import lilock.cn.common.ribbon.constant.ApplicationServiceConstants;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

//FeignClient实现了FallbackFactory
@FeignClient(value = ApplicationServiceConstants.LILOCK_CMS_WEB,configuration = {FeignConfig.class},fallbackFactory = ApiCmsHystrixServiceFeignClientFallbackFactory.class)
public interface ApiCmsHystrixServiceFeignClient {

    @GetMapping("/getHystrix")
    BaseResult<String> getHystrix();

    @GetMapping("/getHystrixTimeOut")
    @HystrixCommand
    BaseResult<String> getHystrixTimeOut(@RequestParam long time);
}

                3.1.1 Normal service test

                 3.1.2 Stop the api service test

It can be seen that the service degradation of fallbackFactory is triggered, and the downstream API will continue to be called after the service degradation

                3.1.3 If you continue to simulate frequent calls to the interface, a fuse will be triggered

When the number of downgrades reaches a certain percentage, the interface will trigger a fuse, and will not continue to call the downstream API after the fuse is triggered

 4. Global Hystrix configuration

hystrix:
  command:
    #全局默认配置
    default:
      execution:
        timeout:
          #是否给方法执行设置超时时间,默认为true。一般我们不要改。
          enabled: true
        isolation:
          #配置请求隔离的方式,这里是默认的线程池方式。还有一种信号量的方式semaphore,使用比较少。
          strategy: threadPool
          semaphore:
            maxConcurrentRequests: 1000
          thread:
            #方式执行的超时时间,默认为1000毫秒,在实际场景中需要根据情况设置
            timeoutInMilliseconds: 60000
            #发生超时时是否中断方法的执行,默认值为true。不要改。
            interruptOnTimeout: true
            #是否在方法执行被取消时中断方法,默认值为false。没有实际意义,默认就好!
            interruptOnCancel: false
            #熔断器相关配置
      ##并发执行的最大线程数,默认10
      coreSize: 200
      #说明:是否允许线程池扩展到最大线程池数量,默认为false。
      allowMaximumSizeToDivergeFromCoreSize: true
      #说明:线程池中线程的最大数量,默认值是10。此配置项单独配置时并不会生效,需要启用allowMaximumSizeToDivergeFromCoreSize
      maximumSize: 200
      #说明1:作业队列的最大值,默认值为-1。表示队列会使用SynchronousQueue,此时值为0,Hystrix不会向队列内存放作业。
      #说明2:如果此值设置为一个正int型,队列会使用一个固定size的LinkedBlockingQueue,此时在核心线程池都忙碌的情况下,会将作业暂时存放在此队列内,但是超出此队列的请求依然会被拒绝
      maxQueueSize: 20000
      #设置队列拒绝请求的阀值,默认为5。
      queueSizeRejectionThreshold: 30000

      circuitBreaker:
        #说明:是否启动熔断器,默认为true。我们使用Hystrix的目的就是为了熔断器,不要改,否则就不要引入Hystrix。
        enabled: true
        #说明1:启用熔断器功能窗口时间内的最小请求数,假设我们设置的窗口时间为10秒,
        #说明2:那么如果此时默认值为20的话,那么即便10秒内有19个请求都失败也不会打开熔断器。
        #说明3:此配置项需要根据接口的QPS进行计算,值太小会有误打开熔断器的可能,而如果值太大超出了时间窗口内的总请求数,则熔断永远也不会被触发
        #说明4:建议设置一般为:QPS*窗口描述*60%
        requestVolumeThreshold: 3000
        #说明1:熔断器被打开后,所有的请求都会被快速失败掉,但是何时恢复服务是一个问题。熔断器打开后,Hystrix会在经过一段时间后就放行一条请求
        #说明2:如果请求能够执行成功,则说明此时服务可能已经恢复了正常,那么熔断器会关闭;相反执行失败,则认为服务仍然不可用,熔断器保持打开。
        #说明3:所以此配置的作用是指定熔断器打开后多长时间内允许一次请求尝试执行,官方默认配置为5秒。
        sleepWindowInMilliseconds: 5000
        #说明1:该配置是指在通过滑动窗口获取到当前时间段内Hystrix方法执行失败的几率后,根据此配置来判断是否需要打开熔断器
        #说明2:这里官方的默认配置为50,即窗口时间内超过50%的请求失败后就会打开熔断器将后续请求快速失败掉
        errorThresholdPercentage: 70
        #说明:是否强制启用熔断器,默认false,没有什么场景需要这么配置,忽略!
        forceOpen: false
        #说明:是否强制关闭熔断器,默认false,没有什么场景需要这么配置,忽略!
        forceClosed: false

5. Reference

https://zhuanlan.zhihu.com/p/339535352

https://blog.csdn.net/weixin_40482816/article/details/119215962

Guess you like

Origin blog.csdn.net/u011291990/article/details/129619330