SpringCloud Hystrix熔断器使用方法介绍

目录
  • Hystrix(hi si ju ke si)概述
  • Hystix 主要功能
  • 隔离
  • Hystrix 降级
  • Hystrix降级-服务提供方
  • 初始化程序和Fiegn程序一致
  • Hystrix降级-服务消费方
  • provider与Fiegin一致
  • Hystrix 熔断
  • Hystrix 熔断监控
  • Turbine聚合监控
    • 搭建监控模块
    • 修改被监控模块
    • 启动测试

Hystrix(hi si ju ke si)概述

Hystix 是 Netflix 开源的一个延迟和容错库,用于隔离访问远程服务、第三方库,防止出现级联失败(雪崩)。

雪崩:一个服务失败,导致整条链路的服务都失败的情形。

Hystix 主要功能

  • 隔离
  • 降级
  • 熔断
  • 限流

隔离

  • 线程池隔离
  • 信号量隔离

Hystrix 降级

Hystix 降级:当服务发生异常或调用超时,返回默认数据

Hystrix降级-服务提供方

  • 在服务提供方,引入 hystrix 依赖
  • 定义降级方法
  • 使用 @HystrixCommand 注解配置降级方法
  • 在启动类上开启Hystrix功能:@EnableCircuitBreaker

初始化程序和Fiegn程序一致

需要修改的程序

package com.itheima.provider;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
/**
 * 启动类
 */
@EnableEurekaClient //该注解 在新版本中可以省略
@SpringBootApplication
@EnableCircuitBreaker ///开启Hystrix功能
public class ProviderApp {
    public static void main(String[] args) {
        SpringApplication.run(ProviderApp.class,args);
    }
}

测试的程序

package com.itheima.provider.controller;
import com.itheima.provider.domain.Goods;
import com.itheima.provider.service.GoodsService;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Date;
/**
 * Goods Controller 服务提供方
 */
@RestController
@RequestMapping("/goods")
public class GoodsController {
    @Autowired
    private GoodsService goodsService;
    @Value("${server.port}")
    private int port;
    /**
     * 降级:
     *   1 出现异常
     *   2 调用服务超时
     *      默认1s超时
     *
     *@HystrixCommand(fallbackMethod = "findOne_fallback")
     * fallbackMethod 指定降级后的名称
     * @param id
     * @return
     */
    @GetMapping("/findOne/{id}")
    @HystrixCommand(fallbackMethod = "findOne_fallback",commandProperties = {
            //设置Hystrix的超时时间 默认1s
            @HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds",value = "3000")
    })///指定降级后的方法
    public Goods findOne(@PathVariable("id") int id)  {
        ///1 造个异常
        //int i =3/0;
        try {
            Thread.sleep(2000);//sleep interrupted
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        Goods goods = goodsService.findOne(id);
        goods.setTitle(goods.getTitle() + ":" + port);//将端口号,设置到了 商品标题上
        return goods;
    }
    /**
     * 定义降级放啊
     * 1 方法的返回值需要和原方法一样
     * 2 方法参数需要和原方法一样
     */
    public Goods findOne_fallback(int id) {
        Goods goods = new Goods();
        goods.setTitle("降级了~~~");
        return goods;
    }
}

指定坐标

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

Hystrix降级-服务消费方

  • feign 组件已经集成了 hystrix 组件。
  • 定义feign 调用接口实现类,复写方法,即降级方法
  • 在 @FeignClient 注解中使用 fallback 属性设置降级处理类。
  • 配置开启 feign.hystrix.enabled = true

provider与Fiegin一致

application.yml修改

server:
  port: 9000

eureka:
  instance:
    hostname: localhost # 主机名
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka
spring:
  application:
    name: hystrix-consumer # 设置当前应用的名称。将来会在eureka中Application显示。将来需要使用该名称来获取路径
#开启feign对hystrix支持
feign:
  hystrix:
    enabled: true

ConsumerApp修改

package com.itheima.consumer;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
@EnableDiscoveryClient // 激活DiscoveryClient
@EnableEurekaClient
@SpringBootApplication
@EnableFeignClients //开启Feign的功能
public class ConsumerApp {
    public static void main(String[] args) {
        SpringApplication.run(ConsumerApp.class,args);
    }
}

修改GoodsFeignClient方法

package com.itheima.consumer.feign;
import com.itheima.consumer.domain.Goods;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
@FeignClient(value = "HYSTRIX-PROVIDER",fallback = GoodsFeignClientFallback.class)
public interface GoodsFeignClient {
    @GetMapping("/goods/findOne/{id}")
    public Goods findGoodsById(@PathVariable("id") int id);
}

复写方法

package com.itheima.consumer.feign;
import com.itheima.consumer.domain.Goods;
import org.springframework.stereotype.Component;
/**
 * Fegin 客户端降级处理类
 * 1 定义类 实现Feign 客户端接口
 * 2 使用@Component注解将该类的Bean加入SpringIOC容器
 */
@Component
public class GoodsFeignClientFallback implements  GoodsFeignClient{
    @Override
    public Goods findGoodsById(int id) {
        Goods goods = new Goods();
        goods.setTitle("又被降级了~~");
        return goods;
    }
}

Hystrix 熔断

Hystrix 熔断机制,用于监控微服务调用情况,当失败的情况达到预定的阈值(5秒失败20次),会打开断路器,拒绝所有请求,直到服务恢复正常为止。

  • circuitBreaker.sleepWindowInMilliseconds:监控时间
  • circuitBreaker.requestVolumeThreshold:失败次数
  • circuitBreaker.errorThresholdPercentage:失败率

//设置Hystrix的超时时间 默认1s
@HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds",value = "3000"),
//监控的时间 默认5000ms
@HystrixProperty(name="circuitBreaker.sleepWindowInMilliseconds",value = "1000"),
//失败次数,默认20次
@HystrixProperty(name="circuitBreaker.requestVolumeThreshold",value = "2"),
//失败率 百分之50
@HystrixProperty(name="circuitBreaker.errorThresholdPercentage",value = "100")

Hystrix 熔断监控

  • Hystrix 提供了 Hystrix-dashboard 功能,用于实时监控微服务运行状态。
  • 但是Hystrix-dashboard只能监控一个微服务。
  • Netflix 还提供了 Turbine ,进行聚合监控。

Turbine聚合监控

搭建监控模块

1. 创建监控模块

创建hystrix-monitor模块,使用Turbine聚合监控多个Hystrix dashboard功能,

2. 引入Turbine聚合监控起步依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>hystrix-parent</artifactId>
        <groupId>com.itheima</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>
    <artifactId>hystrix-monitor</artifactId>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
    	<!--单独熔断监控-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-hystrix-dashboard</artifactId>
        </dependency>
		<!--聚合熔断监控-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-turbine</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

3. 修改application.yml

spring:
  application.name: hystrix-monitor
server:
  port: 8769
turbine:
  combine-host-port: true
  # 配置需要监控的服务名称列表
  app-config: hystrix-provider,hystrix-consumer
  cluster-name-expression: "'default'"
  aggregator:
    cluster-config: default
  #instanceUrlSuffix: /actuator/hystrix.stream
eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8761/eureka/

4. 创建启动类

@SpringBootApplication
@EnableEurekaClient
@EnableTurbine //开启Turbine 很聚合监控功能
@EnableHystrixDashboard //开启Hystrix仪表盘监控功能
public class HystrixMonitorApp {
    public static void main(String[] args) {
        SpringApplication.run(HystrixMonitorApp.class, args);
    }
}

修改被监控模块

需要分别修改 hystrix-provider 和 hystrix-consumer 模块:

1、导入依赖:

		<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <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>

2、配置Bean

此处为了方便,将其配置在启动类中。

@Bean
    public ServletRegistrationBean getServlet() {
        HystrixMetricsStreamServlet streamServlet = new HystrixMetricsStreamServlet();
        ServletRegistrationBean registrationBean = new ServletRegistrationBean(streamServlet);
        registrationBean.setLoadOnStartup(1);
        registrationBean.addUrlMappings("/actuator/hystrix.stream");
        registrationBean.setName("HystrixMetricsStreamServlet");
        return registrationBean;
    }

3、启动类上添加注解@EnableHystrixDashboard

@EnableDiscoveryClient
@EnableEurekaClient
@SpringBootApplication
@EnableFeignClients
@EnableHystrixDashboard // 开启Hystrix仪表盘监控功能
public class ConsumerApp {
    public static void main(String[] args) {
        SpringApplication.run(ConsumerApp.class,args);
    }
    @Bean
    public ServletRegistrationBean getServlet() {
        HystrixMetricsStreamServlet streamServlet = new HystrixMetricsStreamServlet();
        ServletRegistrationBean registrationBean = new ServletRegistrationBean(streamServlet);
        registrationBean.setLoadOnStartup(1);
        registrationBean.addUrlMappings("/actuator/hystrix.stream");
        registrationBean.setName("HystrixMetricsStreamServlet");
        return registrationBean;
    }
}

启动测试

1、启动服务:

  • eureka-server
  • hystrix-provider
  • hystrix-consumer
  • hystrix-monitor

2、访问:

在浏览器访问http://localhost:8769/hystrix/ 进入Hystrix Dashboard界面

界面中输入监控的Url地址 http://localhost:8769/turbine.stream,监控时间间隔2000毫秒和title,如下图

  • 实心圆:它有颜色和大小之分,分别代表实例的监控程度和流量大小。如上图所示,它的健康度从绿色、黄色、橙色、红色递减。通过该实心圆的展示,我们就可以在大量的实例中快速的发现故障实例和高压力实例。
  • 曲线:用来记录 2 分钟内流量的相对变化,我们可以通过它来观察到流量的上升和下降趋势。

到此这篇关于SpringCloud Hystrix熔断器使用方法介绍的文章就介绍到这了,更多相关SpringCloud Hystrix熔断器内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • SpringCloud修改Feign日志记录级别过程浅析

    目录 前言 1. 介绍 2. 方式一 3. 方式二 前言 本次示例代码的文件结构如下图所示. 1. 介绍 Feign 允许我们自定义配置,下面是 Feign 可以修改的配置. 类型 作用 说明 feign.Logger.Level 修改日志级别 包含四种不同级别:NONE.BASIC.HEADERS.FULL feign.codec.Decoder 响应结果的解析器 HTTP 远程调用的结果做解析,例如解析 JSON 字符串反序列化成 Java 对象 feign.codec.Encoder 请求

  • 一文吃透Spring Cloud gateway自定义错误处理Handler

    目录 正文 AbstractErrorWebExceptionHandler isDisconnectedClientError方法 isDisconnectedClientErrorMessage方法: 小结 NestedExceptionUtils getRoutingFunction logError write 其他的方法 afterPropertiesSet renderDefaultErrorView renderErrorView DefaultErrorWebExceptionH

  • SpringCloud Gateway动态路由配置详解

    目录 路由 动态 路由模型实体类 动态路径配置 路由模型JSON数据 路由 gateway最主要的作用是,提供统一的入口,路由,鉴权,限流,熔断:这里的路由就是请求的转发,根据设定好的某些条件,比如断言,进行转发. 动态 动态的目的是让程序更加可以在运行的过程中兼容更多的业务场景. 涉及到两个服务,一个是门户服务(作用是提供给运营人员管理入口--包括:管理路由.绑定路由),一个是网关服务(gateway组件,为门户服务提供:查询路由信息.添加路由.删除路由.编辑路由接口). 路由模型实体类 /*

  • SpringCloud Gateway路由组件详解

    目录 简介 核心概念 具体示例 GlobalFilter 简介   Gateway是SpringCloud Alibaba中的路由组件(前身是Zuul),作为浏览器端请求的统一入口.当项目采用微服务模式时,若包含了路由模块,浏览器端的请求都不会直接请求含有业务逻辑的各个业务模块,而是请求这个路由模块,然后再由它来转发到各个业务模块去. 核心概念   Gateway中的三个核心概念:路由.断言(Predicate).过滤器.   路由:由唯一id.目的url.断言和过滤组成   断言:即路由规则,

  • SpringCloud @RefreshScope刷新机制浅析

    目录 一.前言 二.@Scope 三.RefreshScope 的实现原理 四.总结 一.前言 用过Spring Cloud的同学都知道在使用动态配置刷新的我们要配置一个@RefreshScope 在类上才可以实现对象属性的的动态更新,本着知其所以然的态度,晚上没事儿又把这个点回顾了一下,下面就来简单的说下自己的理解. 总览下,实现@RefreshScope 动态刷新的就需要以下几个: @ Scope @RefreshScope RefreshScope GenericScope Scope C

  • springcloud-gateway集成knife4j的示例详解

    目录 springcloud-gateway集成knife4j 环境信息 环境信息 准备工作 网关集成knife4j 编写配置类Knife4jGatewayConfig 测试验证 相关资料 springcloud-gateway集成knife4j 环境信息 环境信息 spring-boot:2.6.3 spring-cloud-alibaba:2021.0.1.0 knife4j-openapi2-spring-boot-starter:4.0.0 准备工作 各微服务&网关引入依赖 <dep

  • Spring Cloud Ribbon 负载均衡使用策略示例详解

    目录 一.前言 二.什么是 Ribbon 2.1 ribbon简介 2.1.1  ribbon在负载均衡中的角色 2.2 客户端负载均衡 2.3 服务端负载均衡 2.4 常用负载均衡算法 2.4.1 随机算法 2.4.2 轮询算法 2.4.3 加权轮询算法 2.4.4 IP地址hash 2.4.5 最小链接数 三.Ribbon中负载均衡策略总探究 3.1 nacos中使用ribbon过程 3.1.1 添加配置类 3.1.2 接口层调用 3.2 Ribbon中负载均衡配置策略 3.2.1 IRul

  • SpringCloud开启session共享并存储到Redis的实现

    目录 一.原架构 二.调整架构以及相应的代码 1.Redis和session的配置 2.增加配置类 3.应答过滤器增加session设置 4.增加控制台处理的过滤器ConsoleFilter 5.前端请求中增加(跨域时) 三.部署模式 1.同域 2.跨域 总结 备注:以下所有的gateway均指SpringCloud Gateway 一.原架构 前端<->gateway<->console后端 原来session是在console-access中维护的,当中间有了一层gateway

  • Spring Cloud Gateway远程命令执行漏洞分析(CVE-2022-22947)

    目录 漏洞描述 环境搭建 漏洞复现 声明:本文仅供学习参考,其中涉及的一切资源均来源于网络,请勿用于任何非法行为,否则您将自行承担相应后果,本人不承担任何法律及连带责任. 漏洞描述 使用Spring Cloud Gateway的应用程序在Actuator端点启用.公开和不安全的情况下容易受到代码注入的攻击.攻击者可以恶意创建允许在远程主机上执行任意远程执行的请求. 当攻击者可以访问actuator API时,就可以利用该漏洞执行任意命令. 影响范围 Spring Cloud Gateway <

  • SpringCloud启动失败问题汇总

    目录 SpringCloud启动失败问题 Nacos配置读取失败 解决方案 总结 SpringCloud启动失败问题 Nacos配置读取失败 org.yaml.snakeyaml.error.YAMLException: java.nio.charset.MalformedInputException: Input length = 1        at org.yaml.snakeyaml.reader.StreamReader.update(StreamReader.java:218) ~

  • springcloud整合openfeign使用实例详解

    目录 一.前言 二.微服务接口之间的调用问题 2.1 Httpclient 2.2 Okhttp 2.3 HttpURLConnection 2.4 RestTemplate 三.openfeign介绍 3.1 什么是 openfeign 3.2  openfeign优势 四.Spring Cloud Alibaba整合OpenFeign 4.1 前置准备 4.2  完整整合步骤 4.2.1 order模块添加feign依赖 4.2.2  添加feign接口类 4.2.3  调整调用的方法 4.

  • SpringCloud使用Feign实现远程调用流程详细介绍

    目录 前言 1. 导入依赖坐标 2. 开启Feign自动装配 3. 声明远程调用 4. 替代RestTemplate 5. 测试 前言 本次示例代码的文件结构如下图所示. 1. 导入依赖坐标 在 order-service 的 pom.xml 文件中导入 Feign 的依赖坐标. <!-- Feign远程调用客户端 --> <dependency> <groupId>org.springframework.cloud</groupId> <artifa

  • SpringCloud @RefreshScope刷新机制深入探究

    目录 梳理过程如下 @RefreshScope ScopedProxyMode RefreshAutoConfiguration NacosConfigService ClientWorker CacheData AbstractSharedListener NacosContextRefresher RefreshEventListener ContextRefresher EventPublishingRunListener RestartListener Java连接nacos后会定时心跳

  • Spring Cloud Alibaba 整合Nacos的详细使用教程

    目录 一.前言 二.常用服务注册中心介绍 2.1 dubbo服务注册示意图 2.2 常用注册中心对比 三.nacos介绍 3.1  什么是nacos 3.2 nacos 特点 3.3 nacos生态链地图 四.nacos部署 4.1 下载安装包 4.2 修改脚本启动模式 4.3  启动nacos 服务 五.Spring Cloud Alibaba 整合Nacos 5.1  Spring Cloud Alibaba版本选型 5.2  实验整合案例说明 5.3  整合完整过程 5.3.1 创建聚合工

  • Spring Cloud Gateway替代zuul作为API网关的方法

    目录 第一,pom文件 第二,项目结构 第三,项目代码和运行截图 运行效果图 参考文档: 本文简要介绍如何使用Spring Cloud Gateway 作为API 网关(不是使用zuul作为网关),关于Spring Cloud Gateway和zuul的性能比较本文不再赘述,基本可以肯定Spring Cloud Finchley版本的gateway比zuul 1.x系列的性能和功能整体要好. 特别提醒:Spring Cloud Finchley版本中,即使你引入了spring-cloud-sta

随机推荐