Skip to content

hystrix的使用

一、hystrix的依赖

<!--            hystrix熔断器依赖-->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
<!--        仪表盘监控依赖  生产一般不需要配置,因为有熔断处理方法-->
 <dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-starter-netflix-hystrix-dashboard</artifactId>
 </dependency>
 <dependency>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-actuator</artifactId>
 </dependency>

二、启动增加注解

新增@EnableCircuitBreaker注解开启熔断,或者新增@SpringCloudApplication,该注解包含@EnableCircuitBreaker(开启熔断)、@SpringBootApplication(boot)和@EnableDiscoveryClient注解。 @EnableDiscoveryClient能够让注册中心能够发现,扫描到该服务。

三、api接口实现

在需要熔断的接口方法里增加注解@HystrixCommand(fallbackMethod = "saveFail"),fallbackMethod 后面的值是当方法调用远程服务出现问题, 要进行熔断的时候。会执行的方法。该方法的签名必须与API注解的签名一致。即方法名称和一个参数列表(方法的参数的顺序和类型)

例如:

java
  @GetMapping("saveProductOrder")
    @HystrixCommand(fallbackMethod = "saveFail")
    public Map<String,Object>  save(@RequestBody Map<String,String> paramsMap){
        Map<String,Object> result = new HashMap<>();
        Long userId = Long.parseLong(paramsMap.get("userId"));
        Long productId = Long.parseLong(paramsMap.get("productId"));
        ProductOrder save = productService.save(userId,productId);
        result.put("code",200);
        result.put("message","操作成功");
        result.put("data", save);
        return result;
    }

    private Map<String,Object> saveFail(Map<String,String> paramsMap){
        Map<String,Object> result = new HashMap<>();
        result.put("code",300);
        result.put("message","系统繁忙");
        return  result;

    }

四、接口调用超时

实现降级,feign里有集成hystrix的内容,但是默认是关闭的,需要开启。需要注意的是,这个connectTimeOut是针对feign的配置,并不是针对hystrix的超时(默认1秒), 这里设置了两秒,如果调用的接口返回超过了1秒hystrix一样会进行降级

五、hystrix的隔离策略

hystrix的默认隔离策略是线程池隔离,包含的策略有:THREAD 线程池隔离 (默认),SEMAPHORE 信号量。

信号量适用于接口并发量高的情况,如每秒数千次调用的情况,导致的线程开销过高,通常只适用于非网络调用,执行速度快。

全部配置如下:

feign:
  hystrix:
    enabled: true
  client:
    config:
      default:
        # 连接超时
        connectTimeout: 2000
        #调用超时
        readTimeout: 2000
hystrix:
  command:
    default:
      execution:
        #禁言调用超时熔断策略,不推荐使用任何接口都可能会存在超时
        timeout:
          enabled: true
        isolation:
          #隔离策略  THREAD 线程池隔离 (默认)  SEMAPHORE 信号量
          strategy: THREAD
          semaphore:
            #隔离策略为 信号量的时候,如果达到最大并发数时,后续请求会被拒绝,默认是10
            maxConcurrentRequests: 10
          thread:
            #建议使用这种方式修改接口调用的超时时间
            timeoutInMilliseconds: 3000
#hystrix仪表盘的监控配置
management:
  endpoints:
    web:
      exposure:
        include: "*"

需要实现feign的API,并且在@FeignClient注解增加fallback的属性对应实现类的class,实现类需要注入到spring容器当中,例如

@FeignClient(name = "product-service",fallback = ProductFollBackClient.class)
public interface ProductOrderClient {

    @GetMapping("/product/getProductById")
    Map<String,Object> getProductById(@RequestParam(value = "productId") Long productId);

}
@Component
public class ProductFollBackClient implements ProductOrderClient {

    @Override public Map<String,Object> getProductById(Long productId){
        System.out.println("调用product-service 降级");
        return null;
    }
}

六、仪表盘监控(生产一般不需要配置,因为有熔断处理方法,如发短信通知等等)

增加配置文件以后,在启动类增加注解@EnableHystrixDashboard 开启仪表盘监控

hystrix仪表盘默认的访问地址:http://ip:端口/hystrix,如http://example.com:9090/hystrix

Hystrix Dashboard输入: http://example.com:9090/actuator/hystrix.stream

配置文件信息:搜索文件spring-configuration-metadata.json,找对应的包,里面有相关application的配置文件信息。

仪表盘是通过server-send-event推送到前端,不断的请求 http://example.com:9090/actuator/hystrix.stream。这是一个长连接的请求。类似直播