一文读懂Spring Cloud-Hystrix

 更新时间:2021年03月03日 10:44:24   投稿:mrr  
这篇文章主要介绍了通过一文读懂Spring Cloud-Hystrix的相关知识,本文分步骤通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

Hystrix概述

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

hystrix可以实现降级和熔断:

  • 降级

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

快速失败

  • 熔断

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

限流

防止故障传播、雪崩效应

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

降级

 

第一步:sp06添加hystrix依赖

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

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

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 注解,指定降级方法名
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<?> 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?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("添加订单失败");
  }
}

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

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

hystrix超时设置:

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

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

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

可在yml中设置超时时间:

hystrix:
 command:
  default:
   execution:
    isolation:
     thread:
      timeoutInMilliseconds: 6000

熔断

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

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

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

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

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

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-actuator</artifactId>
  <version>2.4.0</version>
</dependency>

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

# "*"暴露所有监控端点
management:
 endpoints:
  web:
   exposure:
    include: "*"

第三步:测试actuator健康监控

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

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

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

第二步:添加hystrix dashboard依赖

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

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

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

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

hystrix:
 dashboard:
  proxy-stream-allow-list: localhost

第五步:监控查看

http://localhost:4001/hystrix/

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

输入hystrix监控地址

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

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

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

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

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

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

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

相关文章

  • 浅谈Redis持久化的几种方式

    浅谈Redis持久化的几种方式

    这篇文章主要介绍了浅谈Redis持久化的几种方式,前面说到了Redis持久化的 实现方式主要分为了:快照持久化(RDB)、写日志持久化(AOF)
    ,其中快照持久化方式也就是RDB ,需要的朋友可以参考下
    2023-08-08
  • 详解在Spring中如何使用AspectJ来实现AOP

    详解在Spring中如何使用AspectJ来实现AOP

    这篇文章主要介绍了详解在Spring中如何使用AspectJ来实现AOP,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-06-06
  • spring根据controller中接收请求参数不同走不同service的实现方法

    spring根据controller中接收请求参数不同走不同service的实现方法

    这篇文章主要给大家介绍了关于spring实现根据controller中接收请求参数不同走不同service的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2018-11-11
  • springboot项目开启https协议的项目实现

    springboot项目开启https协议的项目实现

    本文主要介绍了springboot项目开启https协议的项目实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2023-07-07
  • Javaweb基础入门requse原理与使用

    Javaweb基础入门requse原理与使用

    Request对象的作用是与客户端交互,收集客户端的Form、Cookies、超链接,或者收集服务器端的环境变量,接下来本篇将详细讲述
    2021-11-11
  • 利用Java实现简单的猜数字小游戏

    利用Java实现简单的猜数字小游戏

    这篇文章主要为大家详细介绍了如何利用java语言实现猜数字小游戏,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2022-04-04
  • springBoot详细讲解使用mybaties案例

    springBoot详细讲解使用mybaties案例

    MyBatis本是apache的一个开源项目iBatis,2010年这个项目由apache software foundation迁移到了google code,并且改名为MyBatis。2013年11月迁移到Github。iBATIS一词来源于“internet”和“abatis”的组合,是一个基于Java的持久层框架
    2022-05-05
  • 浅谈Java由于不当的执行顺序导致的死锁

    浅谈Java由于不当的执行顺序导致的死锁

    为了保证线程的安全,我们引入了加锁机制,但是如果不加限制的使用加锁,就有可能会导致顺序死锁(Lock-Ordering Deadlock)。本文将会讨论一下顺序死锁的问题。
    2021-06-06
  • Java实现的爬虫抓取图片并保存操作示例

    Java实现的爬虫抓取图片并保存操作示例

    这篇文章主要介绍了Java实现的爬虫抓取图片并保存操作,涉及Java针对页面URL访问、获取、字符串匹配、文件下载等相关操作技巧,需要的朋友可以参考下
    2018-08-08

最新评论