SpringBoot集成hystrix

2023-11-18

hystrix有什么用

  • 资源隔离:包括线程池隔离和信号量隔离,限制调用分布式服务的资源使用,某一个调用的服务出现问题不会影响其他服务调用。
  • 降级机制:超时降级、资源不足时(线程或信号量)降级,降级后可以配合降级接口返回托底数据。
  • 融断:当失败率达到阀值自动触发降级(如因网络故障/超时造成的失败率高),熔断器触发的快速失败会进行快速恢复。
  • 缓存:提供了请求缓存、请求合并实现。

在SpringBoot项目中集成

引入依赖

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

启用hystrix

@EnableCircuitBreaker

使用示例

@Component
@RestController
public class HelloService {
    @RequestMapping("/hi")
    @HystrixCommand(fallbackMethod = "hiFail")
    public String hi(String name){
//        try {
//            Thread.sleep(5000);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
//        throw new RuntimeException("test");
        return "hi "+name;
    }


    public String hiFail(String name){
        return "hiFail "+name;
    }
}

通过注解@HystrixCommand标记方法调用失败或超时时,跳转的fallbackMethod方法

配置监控路径

@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;
}

更多配置示例

配置线程池
@Component
@RestController
public class Hello2Service {
    @RequestMapping("/hello2")
    @HystrixCommand(fallbackMethod = "hiFail", commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "500")
    },
            threadPoolProperties = {
                    @HystrixProperty(name = "coreSize", value = "10"),
                    @HystrixProperty(name = "maxQueueSize", value = "20"),
                    @HystrixProperty(name = "keepAliveTimeMinutes", value = "0"),
                    @HystrixProperty(name = "queueSizeRejectionThreshold", value = "15"),
                    @HystrixProperty(name = "metrics.rollingStats.numBuckets", value = "12"),
                    @HystrixProperty(name = "metrics.rollingStats.timeInMilliseconds", value = "1440")
            })
    public String hi(String name) {
        try {
            Thread.sleep(5);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "hi " + name;
    }


    public String hiFail(String name, Throwable e) {
        if (e != null) {
            e.printStackTrace();
        }
        return "hiFail " + name;
    }
}
配置信号量
@Component
@RestController
public class Hello3Service {
    @RequestMapping("/hello3")
    @HystrixCommand(fallbackMethod = "hiFail", commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "500"),
            @HystrixProperty(name = "execution.isolation.semaphore.maxConcurrentRequests", value = "9"),
            @HystrixProperty(name = "fallback.isolation.semaphore.maxConcurrentRequests", value = "20"),
            @HystrixProperty(name = "execution.isolation.strategy", value ="SEMAPHORE")
    })
    public String hi(String name) {
        try {
            Thread.sleep(5);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "hi " + name;
    }


    public String hiFail(String name, Throwable e) {
        if (e != null) {
            e.printStackTrace();
        }
        return "hiFail " + name;
    }
}

配合feignClient使用

引入依赖

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

在application.properties里面添加配置

feign.hystrix.enabled=true

创建feignClient接口,并指定fallback类,fallback类必须实现该接口

@FeignClient(name ="hystrix-consumer", path = "",url = "http://127.0.0.1:8080/",fallback = IHelloFailback.class)
public interface IHelloClient {
    @RequestMapping("/hi")
    public String hi(@RequestParam("name") String name);
}
@Component
public class IHelloFailback implements IHelloClient {
    @Override
    public String hi(String name) {
        return "Hi,服务异常";
    }
}

启用FeignClient,在启动类添加注解

@EnableFeignClients(basePackages = {"com.example.hj.springcloudhystrixprovider.client"})

默认参数

final class Default implements SetterFactory {

@Override
public HystrixCommand.Setter create(Target<?> target, Method method) {
  String groupKey = target.name();
  String commandKey = Feign.configKey(target.type(), method);
  return HystrixCommand.Setter
      .withGroupKey(HystrixCommandGroupKey.Factory.asKey(groupKey))
      .andCommandKey(HystrixCommandKey.Factory.asKey(commandKey));
}
}

自定义参数

@Bean
public Feign.Builder feignHystrixBuilder() {
    return HystrixFeign.builder().setterFactory(new SetterFactory() {
        @Override
        public HystrixCommand.Setter create(Target<?> target, Method method) {
            return HystrixCommand.Setter
                    .withGroupKey(HystrixCommandGroupKey.Factory.asKey(RemoteProductService.class.getSimpleName()))// 控制 RemoteProductService 下,所有方法的Hystrix Configuration
                    .andCommandPropertiesDefaults(
                            HystrixCommandProperties.Setter().withExecutionTimeoutInMilliseconds(10000) // 超时配置
                    );
        }
    });
}

基本配置

参考官方配置

配置项 默认值 说明
hystrix.command.default.execution.isolation.strategy THREAD 隔离策略,THREAD, SEMAPHORE
hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds 1000 线程超时时间
hystrix.command.default.execution.timeout.enabled true 启用超时设置
hystrix.command.default.execution.isolation.thread.interruptOnTimeout true 线程超时时,是否可被中断
hystrix.command.default.execution.isolation.thread.interruptOnCancel false 线程取消时,是否可被中断
hystrix.command.default.execution.isolation.semaphore.maxConcurrentRequests 10 最大并发信号量
hystrix.command.default.fallback.isolation.semaphore.maxConcurrentRequests 10 最大并发备用信号量
hystrix.command.default.fallback.enabled true 启用fallback
hystrix.command.default.circuitBreaker.enabled true 启用断路器
hystrix.command.default.circuitBreaker.requestVolumeThreshold 20 在一个时间窗口内触发断路器的最小请求量
hystrix.command.default.circuitBreaker.sleepWindowInMilliseconds 5000 触发断路器时,服务休眠时间
hystrix.command.default.circuitBreaker.errorThresholdPercentage 50 触发断路器时,最小错误比率
hystrix.command.default.circuitBreaker.forceOpen false 强制打开断路器
hystrix.command.default.circuitBreaker.forceClosed false 强制关闭断路器
hystrix.command.default.metrics.rollingStats.timeInMilliseconds 10000 数据采集时间段
hystrix.command.default.metrics.rollingStats.numBuckets 10 采集数据份,必须能被timeInMilliseconds整除
hystrix.command.default.metrics.rollingPercentile.enabled true 开启采集滚动百分比
hystrix.command.default.metrics.rollingPercentile.timeInMilliseconds 60000 滚动百分收集时间段
hystrix.command.default.metrics.rollingPercentile.numBuckets 6 滚动百分比收集份数,必须能被timeInMilliseconds整除
hystrix.command.default.metrics.rollingPercentile.bucketSize 100 每份数据的最大统计请求量
hystrix.command.default.metrics.healthSnapshot.intervalInMilliseconds 500 健康检查间隔时间
hystrix.command.default.requestCache.enabled true 开启请求缓存,HystrixRequestCache
hystrix.command.default.requestLog.enabled true 开启请求日志,记录在HystrixRequestLog
hystrix.collapser.default.maxRequestsInBatch Integer.MAX_VALUE 单批次最大请求量
hystrix.collapser.default.timerDelayInMilliseconds 10 批次请求延迟启动时间
hystrix.collapser.default.requestCache.enabled true 开启批次请求缓存, HystrixCollapser.execute(), HystrixCollapser.queue()
hystrix.threadpool.default.coreSize 10 核心线程数
hystrix.threadpool.default.maximumSize 10 最大线程数
hystrix.threadpool.default.maxQueueSize -1 最大阻塞线程队列
hystrix.threadpool.default.queueSizeRejectionThreshold 5 队列上限,超过会拒绝请求
hystrix.threadpool.default.keepAliveTimeMinutes 1 线程保持活跃时间(分钟)
hystrix.threadpool.default.allowMaximumSizeToDivergeFromCoreSize false 启用maximumSize参数
hystrix.threadpool.default.metrics.rollingStats.timeInMilliseconds 10000 线程池数据采集时间段
hystrix.threadpool.default.metrics.rollingStats.numBuckets 10 线程池数据采集份数

可视化组件

视图hystrix-dashboard

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-hystrix-dashboard</artifactId>
</dependency>
@EnableTurbine
@EnableHystrixDashboard

启动工程后,访问路径:http://localhost:9001/hystrix

在打开的页面输入需要监控的链接,如:http://localhost:8081/actuator/hystrix.stream

汇总监控turbine

能够使用turbine的前提条件时,所有的服务必须在同一个服务注册中心(同一个eureka),每个待监控的服务都必须有监控路径(/actuator/hystrix.stream)

添加依赖

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

配置需要监控的服务

在application.properties中添加配置,配置每个需要监控的服务名称

turbine.app-config=turbine,hystrix-provider,hystrix-consumer

启动工程,在打开的页面输入汇总监控链接,如:http://localhost:9001/turbine.stream

启动页面

监控页面

参考

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

SpringBoot集成hystrix 的相关文章

随机推荐

  • 258. Add Digits

    class Solution public int addDigits int num int nRet 0 if num lt 10 return num int nTemp 0 while num 0 nTemp nTemp num 1
  • Python Cheat Sheet -- 速查表

    这是基于Python Crash Course Second Edition的知识速查表 很全面的知识梳理脑图 后面附有下载链接 供大家学习 参考资料 https github com ehmatthes pcc 2e https ehma
  • Java基础知识超详细总结

    1 Java文件格式 Java源文件 java 保存Java源代码 Java字节码文件 class 保存对Java源代码编译之后的内容 2 Java文件运行方式 1 将源代码保存在扩展名为 java的文件中 如果源程序中定义了public类
  • 黑苹果不能使用无线网解决办法

    网上找了很多方法 都不能让我的黑苹果上网 果然还是得靠自己 抱着碰碰运气的态度 通过四叶草 安装驱动 在下图所示的已经安装的驱动中 我可以明确的告诉大家 其中一个是usb上网的驱动 也就是说 可以通过手机usb共享网络 而在这之前 我只能通
  • 从0开始写Vue项目-SpringBoot整合Mybatis-plus实现登录、注册功能

    1 从0开始写Vue项目 环境和项目搭建 慕言要努力的博客 CSDN博客 2 从0开始写Vue项目 Vue2集成Element ui和后台主体框架搭建 慕言要努力的博客 CSDN博客 3 从0开始写Vue项目 Vue页面主体布局和登录 注册
  • Element UI 之坑

    el procomfirm 事件 confirm 低版本的需要改 onConfirm
  • 【华为OD机试 2023 B卷

    在线OJ 已购买本专栏用户 请私信博主开通账号 在线刷题 运行出现 Runtime Error 0Aborted 请忽略 华为OD统一考试A卷 B卷 新题库说明 2023年5月份 华为官方已经将的 2022 0223Q 1 2 3 4 统一
  • 游戏外包开发技术难点分析

    游戏开发涉及多个领域的技术 因此在开发过程中可能会遇到很多技术难点 今天和大家分享一些常见的游戏开发技术难点 希望对大家开发游戏有一定帮助 北京木奇移动技术有限公司 专业的软件外包开发公司 欢迎交流合作 1 图形渲染 游戏开发中的图形渲染技
  • vue从入门到入土--------综合案例

    目录 vue cli 组件库 axios 拦截器 proxy 跨域代理 用户列表案例 总结 vue cli 1 什么是 vue cli vue cli 俗称 vue 脚手架 是 vue 官方提供的 快速生成 vue 工程化项目的工具 vue
  • python基础六:列表

    1 序列 1 1基本概念 序列就是python中最基本的一种数据结构 用于保存一组有序的数据 所有的数据在序列当中都会有唯一的一个位置 索引 与之对应 并且序列会按照数据添加的顺序来分配索引 1 2序列的分类 可变序列 序列中的元素可以改变
  • Pycharm里如何调整代码字体大小?

    步骤一 我们在桌面上找到Pycharm 并将其打开 步骤二 打开pycharm之后 我们点击左上角的file选项 也就是文件的选项 步骤三 在文件的选项下 我们选择settings的选项 然后打开settings的窗口页面 步骤四 进入到s
  • ssh怎么访问服务器文件,ssh本地访问远程服务器文件

    ssh本地访问远程服务器文件 内容精选 换一换 Cloud Init工具安装完成后 请参考本节操作配置Cloud Init工具 已安装Cloud Init工具 已为云服务器绑定弹性公网IP 已登录云服务器 云服务器的网卡属性为DHCP方式
  • Linux 经典面试题

    1 下面关于pthread线程相关的 说法正确的是 a 线程是可以通过pthread create来创建 b 在线程中使用usleep 50 1000 一定是精确无误地休眠50毫秒 c 如果有个全局变量在没有加锁保护的情况下被两个线程同时访
  • JavaScript实现数据结构 -- 链表

    文章目录 链表 链表的特点 链表和数组的区别 JS模拟链表 遍历链表 插入节点 删除节点 链表应用 删除链表中的节点 leetcode 237 思路 代码 反转链表 leetcode 206 思路 代码 链表 链表和数组一样是有多个元素组成
  • UE5 利用Project Launcher快速打包

    一 打开Project Launcher 二 Add Custom Launch Profiles 三 打包设置 Project 选择当前项目或者AnyProject都行 看自己需求 Build Build Configuration根据需
  • Substance Painter - Blender - UE4/5 低模 高模 烘焙 ID 流程

    问题1 ID材质 顶点绘制 在Blender中的准备工作 1 选中需要填色的元素 反选隐藏后 进入顶点绘制模式 打开顶点选择模式 按A全选后 选好颜色 按shift K 填充颜色 2 颜色都上好后 进入材质编辑 增加输入的顶点颜色 选好顶点
  • 【计算机视觉

    文章目录 一 检测相关 11篇 1 1 Perspective aware Convolution for Monocular 3D Object Detection 1 2 SCoRD Subject Conditional Relati
  • 回溯算法题(5)组合总和II

    目录 组合总和II 描述 示例 1 示例 2 提示 方法 回溯 组合总和II 描述 给定一个候选人编号的集合 candidates 和一个目标数 target 找出 candidates 中所有可以使数字和为 target 的组合 cand
  • 杂谈随感-2:创新是革新还是革命?

    革新 通常来自于一个系统内部 来自于现有系统的既得利益者 来自于系统内深谙其道的人 来自于系统内深根细作的人 革新者的首要目标是维持现有系统的存在和现有系统大多数人的利益 其二才是革新 革新的目标也是维持现有系统长期存在和发展 一个对现有系
  • SpringBoot集成hystrix

    文章目录 hystrix有什么用 在SpringBoot项目中集成 更多配置示例 配置线程池 配置信号量 配合feignClient使用 基本配置 可视化组件 视图hystrix dashboard 汇总监控turbine 参考 hystr