SpringCloud第四篇-Hystrix

来源:互联网 发布:广数980g75编程实列 编辑:程序博客网 时间:2024/06/16 15:14

Hystrix简介

在分布式环境中实现隔离、熔断,由于在分布式服务中许多服务依赖项中的一些将不可避免地失败。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注解开启Hystrixpublic 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. */@Servicepublic 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: 8764spring:  application:    name: service-hystrixeureka:  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: 8765spring:  application:    name: service-feign-hystrixeureka:  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. */@Componentpublic 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();    }}

这里写图片描述

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

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

这里写图片描述

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

下一篇如何出现监控信息

参考资料监控Hystrix

阅读全文
0 0