当前位置: 移动技术网 > IT编程>开发语言>Java > SpringCloud系列-整合Hystrix的两种方式

SpringCloud系列-整合Hystrix的两种方式

2019年10月17日  | 移动技术网IT编程  | 我要评论
Hystrix [hɪst'rɪks],中文含义是豪猪,因其背上长满棘刺,从而拥有了自我保护的能力。本文所说的Hystrix是Netflix开源的一款容错框架,同样具有自我保护能力。 本文目录 一、Hystrix简介二、Hystrix的设计原则三、Hystrix的工作原理四、Ribbon中使用熔断器 ...

hystrix [hɪst'rɪks],中文含义是豪猪,因其背上长满棘刺,从而拥有了自我保护的能力。本文所说的hystrix是netflix开源的一款容错框架,同样具有自我保护能力。

本文目录

一、hystrix简介二、hystrix的设计原则三、hystrix的工作原理四、ribbon中使用熔断器五、feign中使用熔断器

一、hystrix简介

hystrix是由netflix开源的一个延迟和容错库,用于隔离访问远程系统、服务或者第三方库,防止级联失败,从而提升系统的可用性、容错性与局部应用的弹性,是一个实现了超时机制和断路器模式的工具类库。

二、hystrix的设计原则

  • 防止任何单独的依赖耗尽资源(线程)
    过载立即切断并快速失败,防止排队
  • 尽可能提供回退以保护用户免受故障
  • 使用隔离技术(例如隔板,泳道和断路器模式)来限制任何一个依赖的影响
  • 通过近实时的指标,监控和告警,确保故障被及时发现
  • 通过动态修改配置属性,确保故障及时恢复
  • 防止整个依赖客户端执行失败,而不仅仅是网络通信

三、hystrix的工作原理

  • 使用命令模式将所有对外部服务(或依赖关系)的调用包装在hystrixcommand或hystrixobservablecommand对象中,并将该对象放在单独的线程中执行。
  • 每个依赖都维护着一个线程池(或信号量),线程池被耗尽则拒绝请求(而不是让请求排队)。
  • 记录请求成功,失败,超时和线程拒绝。
  • 服务错误百分比超过了阈值,熔断器开关自动打开,一段时间内停止对该服务的所有请求。
  • 请求失败,被拒绝,超时或熔断时执行降级逻辑。
  • 近实时地监控指标和配置的修改。

当使用hystrix封装每个基础依赖项时,每个依赖项彼此隔离,受到延迟时发生饱和的资源的限制,并包含回退逻辑,该逻辑决定了在依赖项中发生任何类型的故障时做出什么响应。

四、ribbon中使用熔断器

按照下面步骤改造之前的项目spring-cloud-consumer-ribbon

  1. pom.xml引入jar包
<!-- 整合hystrix -->
        <dependency>
            <groupid>org.springframework.cloud</groupid>
            <artifactid>spring-cloud-starter-netflix-hystrix</artifactid>
        </dependency>
  1. 启动类上添加@enablehystrix注解

在启动类上添加@enablehystrix注解开启hystrix的熔断器功能,改造后启动类如下:

@enablehystrix //在启动类上添加@enablehystrix注解开启hystrix的熔断器功能。
@enableeurekaclient
@springbootapplication
public class ribbonconsumerapplication {

    //当添加@loadbalanced注解,就代表启动ribbon,进行负载均衡
    @loadbalanced
    @bean
    public resttemplate resttemplate() {
        return new resttemplate();
    }

    public static void main(string[] args) {
        springapplication.run(ribbonconsumerapplication.class, args);
    }

}
  1. 添加hystrixconsumercontroller

在需要有熔断机制的方法上添加 @hystrixcommand,属性fallbackmethod是熔断时返回的方法,编写完成后hystrixconsumercontroller.java代码如下:

/**
 * 消费者
 */
@slf4j
@restcontroller
@requestmapping("/hystrix/consumer")
public class hystrixconsumercontroller {

    @autowired
    private resttemplate resttemplate;

    /**
     * 调用 user微服务
     */
    @hystrixcommand(fallbackmethod = "getdefaultuser")
    @getmapping("getuser")
    public string getuser(integer id) {
        string url = "http://user-service/provider/getuser?id=" + id;
        return resttemplate.getforobject(url, string.class);
    }

    public string getdefaultuser(integer id) {
        system.out.println("熔断,默认回调函数");
        return "{\"id\":-1,\"name\":\"熔断用户\",\"password\":\"123456\"}";
    }
}
  1. 开始测试

代码编写之后,按顺序启动spring-cloud-eureka、spring-cloud-user-service和spring-cloud-consumer-ribbon,此时打开浏览器访问http://www.lhsxpumps.com/_localhost:8082/hystrix/consumer/getuser?id=2,服务正常,截图如下:


服务正常截图

然后停服务spring-cloud-user-service,再次访问访问http://www.lhsxpumps.com/_localhost:8082/hystrix/consumer/getuser?id=2,此时会触发熔断,截图如下:


触发熔断后截图

五、feign中使用熔断器

feign在整合到spring cloud时已经自带了hystrix模块,所以pom.xml中不需要额外引入feign依赖。

新建一个spring boot项目spring-cloud-consumer-fegin-hystrix,按照下面步骤操作。

  1. application.yml中开启熔断器
server:
  port: 8082 #服务端口
eureka:
  client:
    serviceurl:
      defaultzone: http://localhost:9001/eureka/
spring:
  application:
    name: fegin-hystrix-consumer

feign:
      hystrix:
        # feign熔断器开关
        enabled: true
  1. 新建一个feignclient接口

新建一个feignclient接口userfeginservice并指定fallback,代码如下:

//表示"user-service"的服务,指定fallback
@feignclient(value = "user-service", fallback = userfeginfailbackimpl.class)
public interface userfeginservice {

    @requestmapping(value = "/provider/getuser")
    public string getuser(@requestparam("id") integer id);
}

@feignclient注解参数说明:

  • name:指定feignclient的名称,如果项目使用了ribbon,name属性会作为微服务的名称,用于服务发现。

  • fallback: 定义容错的处理类,当调用远程接口失败或超时时,会调用对应接口的容错逻辑,fallback指定的类必须实现@feignclient标记的接口。

  • fallbackfactory: 工厂类,用于生成fallback类示例,通过这个属性我们可以实现每个接口通用的容错逻辑,减少重复的代码

  • path: 定义当前feignclient的统一前缀,类似于注解到类上的@requestmapping的功能

  1. 添加熔断处理类userfeginfailbackimpl

代码如下:

@slf4j
@component
public class userfeginfailbackimpl implements userfeginservice {

    @override
    public string getuser(integer id) {
        log.info("熔断,默认回调函数");
        return "{\"id\":-1,\"name\":\"熔断用户\",\"msg\":\"请求异常,返回熔断用户!\"}";
    }
}
  1. 添加controller

添加feginhystrixcontroller,用于调用user-service,代码如下:

@restcontroller
@requestmapping("/hystrix/consumer")
public class feginhystrixcontroller {

    @autowired
    private userfeginservice userfeginservice;

    @getmapping("/getuser")
    public string getuser(integer id) {
        return userfeginservice.getuser(id);
    }
}

5 开始测试

代码编写之后,按顺序启动spring-cloud-eureka、spring-cloud-user-service和spring-cloud-consumer-fegin-hystrix,此时打开浏览器访问http://www.lhsxpumps.com/_localhost:8082/hystrix/consumer/getuser?id=2,服务正常,截图如下:


服务正常截图

然后停服务spring-cloud-user-service,再次访问访问http://www.lhsxpumps.com/_localhost:8082/hystrix/consumer/getuser?id=2,此时会触发熔断,截图如下:


触发熔断后截图

六、踩到的坑

  1. hystrix的异常fallback method wasn't found

出现这个异常是因为指定的备用方法和原方法的参数个数或类型不同造成的,所以需要统一参数的类型和个数。

到此springcloud两种方式整合hystrix的功能已经全部实现,有问题欢迎留言沟通哦!

完整源码地址: https://github.com/suisui2019/springboot-study

推荐阅读

1.springcloud系列-利用feign实现声明式服务调用)
2.手把手带你利用ribbon实现客户端的负载均》
3.springcloud搭建注册中心与服务注册
4.spring boot配置过滤器的两种方式!
5.编码神器lombok,学会后开发效率至少提高一倍!


限时领取免费java相关资料,涵盖了java、redis、mongodb、mysql、zookeeper、spring cloud、dubbo/kafka、hadoop、hbase、flink等高并发分布式、大数据、机器学习等技术。
关注下方公众号即可免费领取:

java碎碎念公众号java碎碎念公众号

 

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网