
Spring Cloud --- Hystrix(容错工具)
发布日期:2021-05-20 01:12:06
浏览次数:17
分类:精选文章
本文共 6724 字,大约阅读时间需要 22 分钟。
Hystrix 解析
1. Hystrix 断路器
1.1 微服务宕机时,ribbon 无法转发请求
关闭 user-service
和 order-service
。
图片描述:79253124f84b080b945e0bad.jpg
1.2 项目创建
复制 sp06-ribbon
项目至 sp07-hystrix
,关闭原项目。
图片描述:a70143563e516277aecf4a5.jpg
1.2.1 pom.xml 修改
添加 Spring Cloud Netlix Hystrix 依赖。
图片描述:b0084b145da1f621b293e5ec.jpg
1.2.2 application.yml 配置
添加 Hystrix 配置,启用断路器。
图片描述:c9014cc5d5d72f5db6b2c56.jpg
1.2.3 主程序注解
使用 @EnableCircuitBreaker
启用断路器。
代码示例:
package cn.tedu.sp07;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.context.annotation.Bean;import org.springframework.http.client.SimpleClientHttpRequestFactory;import org.springframework.web.client.RestTemplate;@SpringBootApplication@EnableCircuitBreaker@EnableDiscoveryClientpublic class Sp07HystrixApplication { public static void main(String[] args) { SpringApplication.run(Sp07HystrixApplication.class, args); } @LoadBalanced @Bean public RestTemplate getRestTemplate() { SimpleClientHttpRequestFactory f = new SimpleClientHttpRequestFactory(); f.setConnectTimeout(1000); f.setReadTimeout(1000); return new RestTemplate(f); }}
1.3 HystrixController 降级方法
添加 @HystrixCommand
注解并实现降级方法。
代码示例:
package cn.tedu.sp07.controller;import cn.tedu.sp01.pojo.Item;import cn.tedu.sp01.pojo.Order;import cn.tedu.sp01.pojo.User;import cn.tedu.web.util.JsonResult;import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.*;import org.springframework.web.client.RestTemplate;@RestControllerpublic class HystrixController { @Autowired private RestTemplate rt; @GetMapping("/item-service/{orderId}") @HystrixCommand(fallbackMethod = "getItemsFB") public JsonResult
- > getItems(@PathVariable String orderId) { return rt.getForObject("http://item-service/{1}", JsonResult.class, orderId); } @PostMapping("/item-service/decreaseNumber") @HystrixCommand(fallbackMethod = "decreaseNumberFB") public JsonResult decreaseNumber(@RequestBody List
- items) { return rt.postForObject("http://item-service/decreaseNumber", items, JsonResult.class); } @GetMapping("/user-service/{userId}") @HystrixCommand(fallbackMethod = "getUserFB") public JsonResult
getUser(@PathVariable Integer userId) { return rt.getForObject("http://user-service/{1}", JsonResult.class, userId); } @GetMapping("/user-service/{userId}/score") @HystrixCommand(fallbackMethod = "addScoreFB") public JsonResult addScore(@PathVariable Integer userId, Integer score) { return rt.getForObject("http://user-service/{1}/score?score={2}", Paginator.class, userId, score); } @GetMapping("/order-service/{orderId}") @HystrixCommand(fallbackMethod = "getOrderFB") public JsonResult getOrder(@PathVariable String orderId) { return rt.getForObject("http://order-service/{1}", Paginator.class, orderId); } @GetMapping("/order-service") @HystrixCommand(fallbackMethod = "addOrderFB") public JsonResult addOrder() { return rt.getForObject("http://order-service/", Paginator.class); } @HystrixCommand(fallbackMethod = "getItemsFB") public JsonResult getItemsFB(String orderId) { return JsonResult.err().msg("获取订单商品列表失败"); } @HystrixCommand(fallbackMethod = "decreaseNumberFB") public JsonResult decreaseNumberFB(List - items) { return JsonResult.err().msg("更新商品库存失败"); } @HystrixCommand(fallbackMethod = "getUserFB") public JsonResult getUserFB(Integer userId) { return JsonResult.err().msg("获取用户信息失败"); } @HystrixCommand(fallbackMethod = "addScoreFB") public JsonResult addScoreFB(Integer userId, Integer score) { return JsonResult.err().msg("增加用户积分失败"); } @HystrixCommand(fallbackMethod = "getOrderFB") public JsonResult getOrderFB(String orderId) { return JsonResult.err().msg("获取订单失败"); } @HystrixCommand(fallbackMethod = "addOrderFB") public JsonResult addOrderFB() { return JsonResult.err().msg("添加订单失败"); } }
1.4 Hystrix 超时设置
默认超时为1000ms,建议设置为10秒。
代码示例:
spring: application: name: hystrix server: port: 3001 eureka: client: service-url: defaultZone: http://eureka1:2001/eureka, http://eureka2:2002/eureka ribbon: MaxAutoRetriesNextServer: 2 MaxAutoRetries: 1 OkToRetryOnAllOperations: true hystrix: command: default: execution: isolation: thread: timeoutInMilliseconds: 500
1.5 访问测试
- 检查
item-service
超时失败。 - 检查
user-service
未启动。 - 观察断路器状态。
图片描述:多个断路器测试图示。
2. Hystrix 电路板仪表盘
2.1 项目添加 Actuator
添加 Actuator 依赖并配置暴露端点。
代码示例:
org.springframework.boot spring-boot-starter-actuator
2.1.1 application.yml 配置
暴露 hystrix.stream
端点。
代码示例:
spring: application: name: hystrix server: port: 3002 eureka: client: service-url: defaultZone: http://eureka1:2001/eureka, http://eureka2:2002/eureka ribbon: MaxAutoRetriesNextServer: 1 MaxAutoRetries: 1 OkToRetryOnAllOperations: true hystrix: command: default: execution: isolation: thread: timeoutInMilliseconds: 500 management: endpoints: web: exposure: include: hystrix.stream
2.2 Hystrix 仪表盘
独立搭建仪表盘项目,配置监控路径。
代码示例:
package cn.tedu.sp08;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.cloud.client.discovery.EnableDiscoveryClient;import org.springframework.cloud.netflix.hystrix.dashboard.EnableHystrixDashboard;@SpringBootApplication@EnableHystrixDashboardpublic class Sp08HystrixDashboardApplication { public static void main(String[] args) { SpringApplication.run(Sp08HystrixDashboardApplication.class, args); }}
2.3 测试
通过 ab 工具进行高并发测试,观察断路器状态。
命令示例:
ab -n 20000 -c 50 http://localhost:3002/item-service/35
2.4 Hystrix 配置
调整配置参数以优化系统响应。
常用配置:
hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds
hystrix.command.default.circuitBreaker.requestVolumeThreshold
hystrix.command.default.circuitBreaker.errorThresholdPercentage
hystrix.command.default.circuitBreaker.sleepWindowInMilliseconds
完整文档:Hystrix官方文档
发表评论
最新留言
留言是一种美德,欢迎回访!
[***.207.175.100]2025年05月04日 02时14分12秒
关于作者

喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
教程丨使用MeterSphere做Dubbo接口测试
2019-03-16
【毕设-STM32f103寄存器版本】智能防盗系统
2019-03-16
勒索病毒Kraken2.0.7分析
2019-03-16
MySQL错误1366处理方法
2019-03-16
pytorch深度学习中每个epoch运行时间的统计代码
2019-03-16
VxWorks 操作系统学习笔记
2019-03-16
链表插入和删除算法
2019-03-16
断言(assert)的用法
2019-03-16
主机与虚拟机(ubuntu)可以互ping,虚拟机不能上网解决办法
2019-03-16
驱动程序之_1_字符设备_13_USB设备_1_基本概念
2019-03-16
wxPython下载安装教程
2019-03-16
HERest源码解析
2019-03-16
java 原型模式(大话设计模式)
2019-03-16
微机原理 6-计算机中常用的数制
2019-03-16
web访问ejb测试 详解
2019-03-16
window系统下安装使用curl命令工具
2019-03-16
假如计算机是中国人发明的,那代码应该这么写
2019-03-16
神器 Codelf !
2019-03-16