热门标签 | HotTags
当前位置:  开发笔记 > 前端 > 正文

一文读懂SpringCloud-Hystrix

这篇文章主要介绍了通过一文读懂SpringCloud-Hystrix的相关知识,本文分步骤通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

Hystrix概述

Hystrix:断路器,容错管理工具,旨在通过熔断机制控制服务和第三方库的节点,从而对延迟和故障提供更强大的容错能力。

hystrix可以实现降级和熔断:

  • 降级

调用远程服务失败(宕机、500错、超时),可以降级执行当前服务中的一段代码,向客户端返回结果

快速失败

  • 熔断

当访问量过大,出现大量失败,可以做过热保护,断开远程服务不再调用

限流

防止故障传播、雪崩效应

在微服务系统中,服务之间进行依赖,避免有调用其中服务失败,而引起其他服务大范围宕机,造成雪崩效应,hystrix熔断可在满足熔断条件(默认10秒20次以上请求,同时50%失败)后执行降级。快速断开故障服务,保护其他服务不受影响。

降级

 

第一步:sp06添加hystrix依赖

1
2
3
4
<dependency>
  <groupid>org.springframework.cloud</groupid>
  <artifactid>spring-cloud-starter-netflix-hystrix</artifactid>
</dependency>

第二步:主程序添加 @EnableCircuitBreaker 启用 hystrix 断路器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
package cn.tedu.sp06;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
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;
@EnableCircuitBreaker
@SpringBootApplication
public class Sp06RibbonApplication {
  public static void main(String[] args) {
   SpringApplication.run(Sp06RibbonApplication.class, args);
  }
  /**
 * 创建RestTemplate实例
 * 放入spring容器
 * @LoadBalanced-对RestTemplate进行增强,封装RestTemplate,添加负载均衡功能
 */
 @LoadBalanced
 @Bean public RestTemplate restTemplate(){
   //设置调用超时时间,超时后认为调用失败
 SimpleClientHttpRequestFactory f =
      new SimpleClientHttpRequestFactory();
   f.setConnectTimeout(1000);//建立连接等待时间
 f.setReadTimeout(1000);//连接建立后,发送请求后,等待接收响应的时间
 return new RestTemplate(f);
  }
}

第三步:RibbonController 中添加降级方法

  • 为每个方法添加降级方法,例如 getItems() 添加降级方法 getItemsFB()
  • 添加 @HystrixCommand 注解,指定降级方法名
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package cn.tedu.sp06.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 lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import java.util.List;
@RestController
@Slf4j
public class RibbonController {
  @Autowired
 private RestTemplate rt;
  @GetMapping("/item-service/{orderId}")
  @HystrixCommand(fallbackMethod = "getItemsFB") //指定降级方法的方法名
 public JsonResult<list<item>> getItems(@PathVariable String orderId){
    return rt.getForObject("http://item-service/{1}", JsonResult.class,orderId);
  }
  @PostMapping("/item-service/decreaseNumber")
  @HystrixCommand(fallbackMethod = "decreaseNumberFB") //指定降级方法的方法名
 public JsonResult<&#63;> decreaseNumber(@PathVariable List<item> items){
    return rt.postForObject("http://item-service/decreaseNumber",items, JsonResult.class);
  }
  @GetMapping("/user-service/{userId}")
  @HystrixCommand(fallbackMethod = "getUserFB") //指定降级方法的方法名
 public JsonResult<user> 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&#63;score={2}", JsonResult.class, userId, score);
  }
  @GetMapping("/order-service/{orderId}")
  @HystrixCommand(fallbackMethod = "getOrderFB") //指定降级方法的方法名
 public JsonResult<order> getOrder(@PathVariable String orderId) {
    return rt.getForObject("http://order-service/{1}", JsonResult.class, orderId);
  }
  @GetMapping("/order-service")
  @HystrixCommand(fallbackMethod = "addOrderFB") //指定降级方法的方法名
 public JsonResult addOrder() {
    return rt.getForObject("http://order-service/", JsonResult.class);
  }
  //降级方法的参数和返回值,需要和原始方法一致,方法名任意
 public JsonResult<list<item>> getItemsFB(String orderId) {
    return JsonResult.err("获取订单商品列表失败");
  }
  public JsonResult decreaseNumberFB(List<item> items) {
    return JsonResult.err("更新商品库存失败");
  }
  public JsonResult<user> getUserFB(Integer userId) {
    return JsonResult.err("获取用户信息失败");
  }
  public JsonResult addScoreFB(Integer userId, Integer score) {
    return JsonResult.err("增加用户积分失败");
  }
  public JsonResult<order> getOrderFB(String orderId) {
    return JsonResult.err("获取订单失败");
  }
  public JsonResult addOrderFB() {
    return JsonResult.err("添加订单失败");
  }
}</order></user></item></list<item></order></user></item></list<item>

第四步:启动eureka、item和hystrix服务器进行测试

http://localhost:3001/item-service/35

hystrix超时设置:

超时时间设置应该超过ribbon重试时间,否则重试失效。

1
hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds

hystrix等待超时后, 会执行降级代码, 快速向客户端返回降级结果, 默认超时时间是1000毫秒。

可在yml中设置超时时间:

1
2
3
4
5
6
7
hystrix:
 command:
  default:
   execution:
    isolation:
     thread:
      timeoutInMilliseconds: 6000

熔断

主程序添加 @EnableCircuitBreaker 启用 hystrix 断路器,熔断自动打开。

Hystrix故障监控-Hystrix Dashboard断路器仪表盘

Hystrix使用springboot提供的actuator健康管理,监控各个端点。

actuator中的hystrix.stream可以监控hystrix断路器各端点日志。

第一步:sp06的pom中添加actuator依赖

1
2
3
4
5
<dependency>
  <groupid>org.springframework.boot</groupid>
  <artifactid>spring-boot-starter-actuator</artifactid>
  <version>2.4.0</version>
</dependency>

第二步:在yml中配置健康监控的内容

1
2
3
4
5
6
# "*"暴露所有监控端点
management:
 endpoints:
  web:
   exposure:
    include: "*"

第三步:测试actuator健康监控

http://localhost:3001/actuator/ 搭建Hystrix Dashboard仪表盘:

仪表盘项目是一个完全独立的项目。

第一步:创建springboot项目sp08-htstrix-dashboard

第二步:添加hystrix dashboard依赖

1
2
3
4
<dependency>
  <groupid>org.springframework.cloud</groupid>
  <artifactid>spring-cloud-starter-netflix-hystrix-dashboard</artifactid>
</dependency>

第三步:主程序上添加@EnableHystrixDashboard注解

1
2
3
4
5
6
7
8
9
10
11
package cn.tedu.sp08;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.hystrix.dashboard.EnableHystrixDashboard;
@EnableHystrixDashboard
@SpringBootApplication
public class Sp08HystrixDashboardApplication {
  public static void main(String[] args) {
   SpringApplication.run(Sp08HystrixDashboardApplication.class, args);
  }
}

第四步:配置允许给那些服务器开启权限

1
2
3
hystrix:
 dashboard:
  proxy-stream-allow-list: localhost

第五步:监控查看

http://localhost:4001/hystrix/

第六步:查看hystrix stream监控数据端点

输入hystrix监控地址

访问item/user/order服务器,查看仪表盘。

第六步:使用ab进行并发访问测试

使用 apache 的并发访问测试工具 ab进行访问测试。

打开ab工具/bin文件目录--cmd--输入命令:

1
ab -n 20000 -c 50 http://localhost:3001/item-service/35

并发50,发送20000个请求,查看仪表盘。

到此这篇关于一文读懂Spring Cloud-Hystrix的文章就介绍到这了,更多相关Spring Cloud Hystrix内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!


推荐阅读
  • 本文将详细介绍如何在ThinkPHP6框架中实现多数据库的部署,包括读写分离的策略,以及如何通过负载均衡和MySQL同步技术优化数据库性能。 ... [详细]
  • 深入解析 Apache Shiro 安全框架架构
    本文详细介绍了 Apache Shiro,一个强大且灵活的开源安全框架。Shiro 专注于简化身份验证、授权、会话管理和加密等复杂的安全操作,使开发者能够更轻松地保护应用程序。其核心目标是提供易于使用和理解的API,同时确保高度的安全性和灵活性。 ... [详细]
  • 本文探讨了如何在日常工作中通过优化效率和深入研究核心技术,将技术和知识转化为实际收益。文章结合个人经验,分享了提高工作效率、掌握高价值技能以及选择合适工作环境的方法,帮助读者更好地实现技术变现。 ... [详细]
  • 深入解析Spring Cloud微服务架构与分布式系统实战
    本文详细介绍了Spring Cloud在微服务架构和分布式系统中的应用,结合实际案例和最新技术,帮助读者全面掌握微服务的实现与优化。 ... [详细]
  • 深入理解一致性哈希算法及其应用
    本文详细介绍了分布式系统中的一致性哈希算法,探讨其原理、优势及应用场景,帮助读者全面掌握这一关键技术。 ... [详细]
  • 本文详细介绍了 Flink 和 YARN 的交互机制。YARN 是 Hadoop 生态系统中的资源管理组件,类似于 Spark on YARN 的配置方式。我们将基于官方文档,深入探讨如何在 YARN 上部署和运行 Flink 任务。 ... [详细]
  • MySQL 高性能实战教程
    本课程深入探讨 MySQL 的架构、性能调优、索引优化、查询优化及高可用性等关键领域。通过实际案例和详细讲解,帮助学员掌握提升 MySQL 数据库性能的方法与技巧。 ... [详细]
  • 本文介绍了数据库体系的基础知识,涵盖关系型数据库(如MySQL)和非关系型数据库(如MongoDB)的基本操作及高级功能。通过三个阶段的学习路径——基础、优化和部署,帮助读者全面掌握数据库的使用和管理。 ... [详细]
  • Nginx 反向代理与负载均衡实验
    本实验旨在通过配置 Nginx 实现反向代理和负载均衡,确保从北京本地代理服务器访问上海的 Web 服务器时,能够依次显示红、黄、绿三种颜色页面以验证负载均衡效果。 ... [详细]
  • 在项目中使用 Redis 时,了解其不同架构模式(如单节点、主从复制、哨兵模式和集群)对于确保系统的高可用性和扩展性至关重要。本文将详细探讨这些模式的特点和应用场景。 ... [详细]
  • 使用LVS与ldirectord实现高可用负载均衡
    本文介绍了如何通过LVS(Linux Virtual Server)结合ldirectord工具来实现服务器的健康检查及负载均衡功能。环境设置包括一个LVS节点和两个真实服务器节点,通过配置ldirectord进行健康状态监测,确保系统的高可用性。 ... [详细]
  • 深入理解Docker网络管理
    本文介绍了Docker网络管理的基本概念,包括为什么需要Docker网络管理以及Docker提供的多种网络驱动模式。同时,文章还详细解释了Docker网络相关的命令操作,帮助读者更好地理解和使用Docker网络功能。 ... [详细]
  • 探讨GET与POST请求数据传输的最大容量
    在Web开发领域,GET和POST是最常见的两种数据传输方法。本文将深入探讨这两种请求方式在不同环境下的数据传输能力及其限制。 ... [详细]
  • 本文提供了一套实用的方法论,旨在帮助开发者构建能够应对高并发请求且易于扩展的Web服务。内容涵盖了服务器架构、数据库管理、缓存策略以及异步处理等多个方面。 ... [详细]
  • 一面问题:MySQLRedisKafka线程算法mysql知道哪些存储引擎,它们的区别mysql索引在什么情况下会失效mysql在项目中的优化场景&# ... [详细]
author-avatar
推广中医
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有