SpringCloud第四篇-Hystrix

Hystrix简介

在介绍熔断机制之前,我们需要了解微服务的雪崩效应。在微服务架构中,微服务是完成一个单一的业务功能,这样做的好处是可以做到解耦,每个微服务可以独立演进。但是,一个应用可能会有多个微服务组成,微服务之间的数据交互通过远程过程调用完成。这就带来一个问题,假设微服务A调用微服务B和微服务C,微服务B和微服务C又调用其它的微服务,这就是所谓的“扇出”。如果扇出的链路上某个微服务的调用响应时间过长或者不可用,对微服务A的调用就会占用越来越多的系统资源,进而引起系统崩溃,所谓的“雪崩效应”。

熔断机制是应对雪崩效应的一种微服务链路保护机制。我们在各种场景下都会接触到熔断这两个字。高压电路中,如果某个地方的电压过高,熔断器就会熔断,对电路进行保护。股票交易中,如果股票指数过高,也会采用熔断机制,暂停股票的交易。同样,在微服务架构中,熔断机制也是起着类似的作用。当扇出链路的某个微服务不可用或者响应时间太长时,会进行服务的降级,进而熔断该节点微服务的调用,快速返回错误的响应信息。当检测到该节点微服务调用响应正常后,恢复调用链路。

在Spring Cloud框架里,熔断机制通过Hystrix实现。Hystrix会监控微服务间调用的状况,当失败的调用到一定阈值,缺省是5秒内20次调用失败,就会启动熔断机制

在dubbo中也可利用nio超时+失败次数做熔断

在分布式环境中实现隔离、熔断,由于在分布式服务中许多服务依赖项中的一些将不可避免地失败。Hystrix是一个库,通过添加延迟容差和容错逻辑来帮助您控制这些分布式服务之间的交互。Hystrix通过隔离服务之间的访问点,停止其间的级联故障以及提供回退选项,从而提高系统的整体弹性。

Netflix has created a library called Hystrix that implements the circuit breaker pattern. In a microservice architecture it is common to have multiple layers of service calls.
—-摘自官网

hystrix通过服务隔离、熔断(也可以称为断路)、降级等手段控制依赖服务的延迟与失败。

Netflix开源了Hystrix组件,实现了断路器模式,SpringCloud对这一组件进行了整合。 在微服务架构中,一个请求需要调用多个服务是非常常见的,如下图:
这里写图片描述

较底层的服务如果出现故障,会导致连锁故障。当对特定的服务的调用的不可用达到一个阀值(Hystric 是5秒20次) 断路器将会被打开。
这里写图片描述

Hystrix旨在执行以下操作

  • 对通过第三方客户端库访问(通常通过网络)的依赖关系提供保护并控制延迟和故障。
  • 隔离复杂分布式系统中的级联故障
  • 快速发现故障,尽快恢复
  • 回退,尽可能优雅地降级
  • 启用近实时监控,警报和操作控制

这里主要演示在Ribbon使用断路器
Feign是自带断路器的,在D版本的Spring Cloud中,它没有默认打开.

项目准备

两个项目依旧使用

  • eureka-server :注册服务
  • service-hello:服务端
  • service-hystrix:客户端(新建项目,Ribbon使用断路器)

Ribbon使用断路器

service-hystrix可以直接拷贝serice-ribbon然后改项目名和pom中的名字。
在pox.xml文件中加入spring-cloud-starter-hystrix的起步依赖:

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-hystrix</artifactId>
</dependency>

在程序的启动类RibbonApplication.java改名字为HystrixApplication.java
在类上加@EnableHystrix注解开启Hystrix:

package com.bamboo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.netflix.hystrix.EnableHystrix;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

/**
 *
 * 客户端
 *
 *  service-hystrix Application
 */
@SpringBootApplication
@EnableDiscoveryClient//向服务中心注册
@EnableHystrix//加@EnableHystrix注解开启Hystrix
public class HystrixApplication {

    public static void main(String[] args) {
        SpringApplication.run(HystrixApplication.class, args);
    }

    @Bean
    @LoadBalanced//开启负载均衡的功能
    RestTemplate restTemplate() {
        return new RestTemplate();
    }

}

使用EnableCircuitBreaker或者 EnableHystrix 表明Spring boot工程启用hystrix,两个注解是等价的.

如果需要加上监控则会加入如下依赖,这里先不加。

        <!--hystrix-dashboard 监控-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-hystrix-dashboard</artifactId>
        </dependency>

在启动类上加入EnableHystrixDashboard注解
表示启动对hystrix的监控

HelloService.java修改如下

package com.bamboo;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

/**
 *
 *1.方法级别的熔断
 *2.类级别的熔断
 *
 * 这里使用的是方法级别的熔断
 * Created by xialeme on 2017/10/20.
 */
@Service
public class HelloService {

    @Autowired
    RestTemplate restTemplate;


    /*********
     * 改造HelloService类,在hiService方法上加上@HystrixCommand注解
     * 该注解对该方法创建了熔断器的功能,并指定了fallbackMethod熔断方法helloError,熔断方法直接返回了一个字符串
     * @param name
     * @return
     */
    @HystrixCommand(fallbackMethod = "helloError")
    public String helloService(String name) {
       // return restTemplate.getForObject("http://SERVICE-HELLO/hello?name="+name,String.class);
        return restTemplate.getForObject("http://SERVICE-HELLO/hello",String.class);
    }



    //熔断回调方法
    public String helloError(String name) {

        return "hello,sorry,error!";
    }

}

最重要的地方在方法体上加上注解
@HystrixCommand(fallbackMethod = “helloError”)

  • 该方法说明此接口使用了熔断命令,如果发生服务终断就调用回调方法helloError
  • 创建helloError方法返回一个字符串

HystrixCommand 表明该方法为hystrix包裹,可以对依赖服务进行隔离、降级、快速失败、快速重试等等hystrix相关功能
该注解属性较多,下面讲解其中几个

  • fallbackMethod 降级方法
  • commandProperties 普通配置属性,可以配置HystrixCommand对应属性,例 如采用线程池还是信号量隔离、熔断器熔断规则等等
  • ignoreExceptions 忽略的异常,默认HystrixBadRequestException不计入失败
  • groupKey() 组名称,默认使用类名称
  • commandKey 命令名称,默认使用方法名

yml

server:
  port: 8764
spring:
  application:
    name: service-hystrix


eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8761/eureka/



其他都不做变动

运行服务并查看接口结果
  • 运行eureka-server
  • 运行service-hello:只用运行一个就可以了
  • 运行service-hystrix

浏览器执行service-hystrix的接口
http://localhost:8764/hello?name=111
可以正常返回数据hello from port:8762
关闭service-hello,再次访问则返回数据
hello,sorry,error!

Feign使用断路器

Feign是自带断路器的,在D版本的Spring Cloud中,它没有默认打开。

基于service-feign工程进行改造,这里创建service-feign-hystrix项目
把service-feign中的pom,yml和java都拷贝进来

需要在配置文件中配置打开它,在配置文件加以下代码:

server:
  port: 8765
spring:
  application:
    name: service-feign-hystrix


eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8761/eureka/

#开启熔断
feign:
  hystrix:
    enabled: true



只需要在FeignClient的SchedualServiceHello 接口的注解中加上fallback的指定类就行了:

package com.bamboo;

import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

/**
 * 定义一个feign接口,通过@ FeignClient(“服务名”),来绑定并指定调用哪个服务
 * value:服务名
 * fallback:熔断回调的类名称
 * Created by babmoo on 2017/10/21.
 */
@FeignClient(value = "service-hello",fallback = HelloServiceHystric.class)
public interface HelloService {

    //使用的springmvc注解
    @RequestMapping(value = "/hello",method = RequestMethod.GET)
    String sayHiFromClientOne(@RequestParam(value = "name") String name);
}

实现fallback 类
HelloServiceHystric.java

package com.bamboo;

import org.springframework.stereotype.Component;

/**
 *
 * 熔断的实现类
 *SchedualServiceHello 接口,并注入到Ioc容器中
 * Created by bamboo on 2017/10/21.
 */
@Component
public class HelloServiceHystric implements HelloService {
    @Override
    public String sayHiFromClientOne(String name) {
        return "sorry "+name;
    }


}

注意:
上面的两个Java文件的类名我都进行了修改,不喜欢以前的名称

启动项目查看结果
  • 只启动eureka-server
  • 启动service-feign-hystrix
    因为我们根本就没有启动service-hello,因此没有这个服务,我们看运行结果是
    http://desktop-180i6sh:8765/hello?name=111
sorry 111

说明已经起作用了

监控Hystrix的信息Hystrix Dashboard

注:这里只是可以打开监控的页面,而实际的监控信息在下一篇中详细讲述

以上两个Hystrix项目使用方法一样
加入依赖,这三个是必加

        <!--hystrix -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-hystrix</artifactId>
        </dependency>

        <!--hystrix-dashboard 监控-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-hystrix-dashboard</artifactId>
        </dependency>


        <!-- 数据监控  -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>

主程序加入注解@EnableHystrixDashboard注解,开启hystrixDashboard

package com.bamboo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.netflix.hystrix.EnableHystrix;
import org.springframework.cloud.netflix.hystrix.dashboard.EnableHystrixDashboard;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

/**
 *ribbon的基础上实现断路器和断路器监控
 * 客户端
 *
 *   service-hystrix Application
 */
@SpringBootApplication
@EnableDiscoveryClient//向服务中心注册
@EnableHystrix//加@EnableHystrix注解开启Hystrix
@EnableHystrixDashboard//开启hystrixDashboard监控信息仪表盘(必加1)
@EnableCircuitBreaker(必加2)
public class HystrixApplication {

    public static void main(String[] args) {
        SpringApplication.run(HystrixApplication.class, args);
    }

    @Bean
    @LoadBalanced//开启负载均衡的功能
    RestTemplate restTemplate() {
        return new RestTemplate();
    }

}


[外链图片转存失败(img-nm2jI1HR-1566618411605)(https://img-blog.csdn.net/20171022001959988?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvempjamF2YQ==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast)]

HystrixApplication 启动后访问http://localhost:8764/hystrix.steam
可以看到返回的json字符串

但是service-feign-hystrix我是如何也看不到这个信息反而和http://localhost:8765/hystrix显示的是同一个页面(有知道原因的可以告诉我)

这里写图片描述

我这里虽然打开了监控页面但是却连不上,爆出:Unable to connect to Command Metric Stream.

下一篇如何出现监控信息

参考资料监控Hystrix

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值