hystrix 是一个专用于服务熔断处理的开源项目,当依赖的服务方出现故障不可用时,hystrix有一个所谓的断路器,一但打开,就会直接拦截掉对故障服务的调用,从而防止故障进一步扩大(类似中电路中的跳闸,保护家用电器)。

使用步骤:(仍然在之前的示例代码上加以改造)

一、添加hystrix依赖

  1. compile 'org.springframework.cloud:spring-cloud-starter-hystrix'

二、在需要熔断的方法上添加注解

  1. package com.cnblogs.yjmyzz.spring.cloud.study.service.controller;
  2.  
  3. import com.cnblogs.yjmyzz.spring.cloud.study.dto.UserDTO;
  4. import com.cnblogs.yjmyzz.spring.cloud.study.service.client.UserFeignClient;
  5. import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
  6. import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
  7. import org.springframework.beans.factory.annotation.Autowired;
  8. import org.springframework.web.bind.annotation.GetMapping;
  9. import org.springframework.web.bind.annotation.PathVariable;
  10. import org.springframework.web.bind.annotation.RestController;
  11.  
  12. import java.util.Random;
  13.  
  14. @RestController
  15. public class OrderController {
  16.  
  17. @Autowired
  18. private UserFeignClient userFeignClient;
  19.  
  20. private final Random rnd = new Random(System.currentTimeMillis());
  21.  
  22. @GetMapping("/order/{userId}/{orderNo}")
  23. @HystrixCommand(fallbackMethod = "findOrderFallback", commandProperties = {
  24. @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "1000")
  25. })
  26. public String findOrder(@PathVariable Integer userId, @PathVariable String orderNo) throws InterruptedException {
  27. Thread.sleep(rnd.nextInt(2000));
  28. UserDTO user = userFeignClient.findUser(userId);
  29. if (user != null) {
  30. return user.getUserName() + " 的订单" + orderNo + " 找到啦!";
  31. }
  32. return "用户不存在!";
  33. }
  34.  
  35. public String findOrderFallback(Integer userId, String orderNo) {
  36. return "订单查找失败!";
  37. }
  38. }  

注意findOrder上添加的HystrixCommand注解,大概意思是,如果这个方法调用失败,会切换到备用方法findOrderFallback上,而且还设置了一个超时时间1000ms,即1秒。换句话说,如果findOrder方法没有在1s内返回结果,也算调用失败,同样会切换到备用方法findOrderFallback上。

注:为了方便演示,故意在findOrder上随机停了2秒内的一段时间,所以预期这个方法,应该会偶尔超时,偶尔正常。

关于HystrixProperty的更多属性,可参考github上的官方文档:https://github.com/Netflix/Hystrix/wiki/Configuration 

三、main入口上启用hytrix熔断

  1. @EnableDiscoveryClient
  2. @SpringBootApplication
  3. @EnableFeignClients
  4. @EnableCircuitBreaker
  5. public class ServiceConsumer {
  6.  
  7. public static void main(String[] args) {
  8. SpringApplication.run(ServiceConsumer.class, args);
  9. }
  10. }  

启用后,访问http://localhost:8002/order/1/100 ,可以看到类似以下输出:

正常时,返回类似上图的输出,如果超时,将返回下图:

此外,spring-boot的acturator也提供了health端点来查看hystrix状态,查看http://localhost:8002/health

这个表示hystrix的断路器未打开,如果 http://localhost:8002/order/1/100 这个页面狂刷(默认要5秒内失败20次以上),或者干脆把service-provider停掉,这个状态会变成:

表明此时断路器是打开的。

四、hystrix监控

health端点只能看到断路器的整体状态,但是对于细节展示不够详细,默认情况下,只要启用了hystrix功能,还会暴露一个端点hystrix.stream

访问 http://localhost:8002/hystrix.stream 可以查看详细的数据

注:这个页面会实时不断输出新的内容(如果有的话),首次访问的话,如果看到一直转圈,但是没有任何内容,说明这时服务对应的方法没人调用,可以访问findOrder方法后,再来看这个页面。

显然,一堆密密麻麻的文字,没有人会喜欢看,spring-cloud早就想到这一点了,提供了一个hystrix-dashboard的功能,可以用图形化的界面来解读这些数据。

再起一个项目,名为hystrix-dashboard,build.gradle参考下面:

  1. buildscript {
  2. repositories {
  3. maven {
  4. url "http://maven.aliyun.com/nexus/content/groups/public/"
  5. }
  6. }
  7. dependencies {
  8. classpath("org.springframework.boot:spring-boot-gradle-plugin:1.5.4.RELEASE")
  9. }
  10. }
  11.  
  12. apply plugin: 'org.springframework.boot'
  13.  
  14. dependencyManagement {
  15. imports {
  16. mavenBom "org.springframework.cloud:spring-cloud-dependencies:Dalston.RELEASE"
  17. }
  18. }
  19.  
  20. dependencies {
  21. compile 'org.springframework.cloud:spring-cloud-starter-eureka'
  22. compile 'org.springframework.cloud:spring-cloud-starter-hystrix-dashboard'
  23. compile 'org.springframework.boot:spring-boot-starter-actuator'
  24. }

main函数如下:

  1. package com.cnblogs.yjmyzz.spring.cloud.study.hystrix;
  2.  
  3. import org.springframework.boot.SpringApplication;
  4. import org.springframework.boot.autoconfigure.SpringBootApplication;
  5. import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
  6. import org.springframework.cloud.netflix.hystrix.dashboard.EnableHystrixDashboard;
  7.  
  8. /**
  9. * Created by yangjunming on 2017/6/30.
  10. */
  11. @SpringBootApplication
  12. @EnableHystrixDashboard
  13. @EnableDiscoveryClient
  14. public class HystrixDashboardApplication {
  15. public static void main(String[] args) {
  16. SpringApplication.run(HystrixDashboardApplication.class, args);
  17. }
  18. }  

当然,这也是一个微服务,也可以注册到eureka上,参考下面的配置:

  1. spring:
  2. application:
  3. name: hystrix-dashboard
  4. server:
  5. port: 8035
  6.  
  7. eureka:
  8. instance:
  9. prefer-ip-address: true
  10. client:
  11. service-url:
  12. defaultZone: http://yjmyzz:123456@server1:8100/eureka,http://yjmyzz:123456@server2:8200/eureka,http://yjmyzz:123456@server3:8300/eureka

启用成功后,访问http://localhost:8035/hystrix,会出现类似下面这个界面:

第1个输入框里,填写要监控的hystrix.steam地址,然后title这里起一个名字即可,然后点击monitor steam,就能看到图表:

这显然比纯文字友好多了。还有一个问题,如果有多个hystrix.stream地址同时监控,或者把多个地址的数据汇总起来,该怎么弄?github上有一个turbine ,就是专门为解决这个问题的,大家可以自行研究下。

最后,附上文中示例代码地址:https://github.com/yjmyzz/spring-cloud-demo

spring cloud 学习(4) - hystrix 服务熔断处理的更多相关文章

  1. Spring Cloud第五篇 | 服务熔断Hystrix

    ​ 本文是Spring Cloud专栏的第五篇文章,了解前四篇文章内容有助于更好的理解本文: Spring Cloud第一篇 | Spring Cloud前言及其常用组件介绍概览 Spring Clo ...

  2. spring cloud学习一--Eureka服务注册与发现

    spring cloud Eureka是基于Netflix Eureka服务发现注册产品的二次封装,它提供了服务注册功能(Service Registry)和服务发现功能(Service Discov ...

  3. Spring Cloud 学习 (四) Hystrix & Hystrix Dashboard & Turbine

    在复杂的分布式系统中,可能有几十个服务相互依赖,这些服务由于某些原因,例如机房的不可靠性.网络服务商的不可靠性等,导致某个服务不可用 . 如果系统不隔离该不可用的服务,可能会导致整个系统不可用.Hys ...

  4. spring cloud学习(二) 调用服务

    spring-cloud调用服务有两种方式,一种是Ribbon+RestTemplate, 另外一种是Feign. Ribbon是一个基于HTTP和TCP客户端的负载均衡器,其实feign也使用了ri ...

  5. spring cloud 学习(9) - turbine stream无法在eureka注册的解决办法

    turbine是啥就不多解释了,初次接触的可以移步spring cloud 学习(4) - hystrix 服务熔断处理 拉到最后看一下,turbine stream默认情况下启动成功后,eureka ...

  6. Spring Cloud第九篇 | 分布式服务跟踪Sleuth

    ​ ​本文是Spring Cloud专栏的第九篇文章,了解前八篇文章内容有助于更好的理解本文: Spring Cloud第一篇 | Spring Cloud前言及其常用组件介绍概览 Spring Cl ...

  7. spring cloud 学习之服务消费者(rest+ribbon)

    学习自 http://blog.csdn.net/forezp/article/details/81040946 方志朋的博客 在微服务架构中,业务都会被拆分成一个独立的服务,服务与服务的通讯是基于h ...

  8. Spring Cloud学习(一):Eureka服务注册与发现

    1.Eureka是什么 Eureka是Netflix开发的服务发现框架,本身是一个基于REST的服务,主要用于定位运行在AWS域中的中间层服务,以达到负载均衡和中间层服务故障转移的目的. Eureka ...

  9. spring cloud + mybatis 分布式 微服务 b2b2c 多商户商城 全球部署方案

    用java实施的电子商务平台太少了,使用spring cloud技术构建的b2b2c电子商务平台更少,大型企业分布式互联网电子商务平台,推出PC+微信+APP+云服务的云商平台系统,其中包括B2B.B ...

随机推荐

  1. linux离线部署redis及redis.conf详解

    一.离线部署redis 由于博主部署的虚拟机没有网络也没有gcc编译器,所以就寻找具备gcc编译器的编译环境把redis编译安装好,Copy Redis安装目录文件夹到目标虚拟机的目录下.copy时r ...

  2. JavaScript 中创建三种消息框:警告框、确认框、提示框。

    网址:http://www.w3school.com.cn/js/js_popup.asp 警告框 警告框经常用于确保用户可以得到某些信息. 当警告框出现后,用户需要点击确定按钮才能继续进行操作. 语 ...

  3. composer "Failed to decode zlib stream"

    dockerFile 中安装composer.... RUN curl -s -f -L -o /tmp/installer.php https://raw.githubusercontent.com ...

  4. Dream------Hadoop--网络拓扑与Hadoop--摘抄

    两个节点在一个本地网络中被称为“彼此的近邻”是什么意思?在高容量数据处理中,限制因素是我们在节点间 传送数据的速率-----带宽很稀缺.这个想法便是将两个节点间的带宽作为距离的衡量标准.   衡量节点 ...

  5. JS种this的四种用法

    记住以下四点: 1.没调用对象就指向全局对象 2.有对象就指向调用对象 3.用new构造就指向新对象 4.通过 apply 或 call 或 bind 来改变 this 的所指. 1.测试一:没调用对 ...

  6. Android启动过程

    1.背景知识                                                          Init进程是Linux环境下非常重要的一个进程,而Zygote进程是J ...

  7. Vmware中Linux或macOS客户端如何回收硬盘空间

    Vmware对于Windows的客户端,使用GUI操作硬盘回收和整理磁盘即可.对于Linux或macOS客户端,需要在安装Vmware Tools之后,在客户端OS的终端Terminal里输入命令进行 ...

  8. Java基础84 javaBean规范

    1.javaBean的概述 1.javaBeam(咖啡豆)是一种开发规范,也可以说是一种技术.  2.JavaBean就是一个普通java类,只要符合以下规定才能称作为javaBean:        ...

  9. redis实现分布式锁服务

    译自Redis官方文档 在多线程共享临界资源的场景下,分布式锁是一种非常重要的组件.许多库使用不同的方式使用redis实现一个分布式锁管理.其中有一部分简单的实现方式可靠性不足,可以通过一些简单的修改 ...

  10. 使用div模拟出frameset效果

    <!doctype html> <html xmlns="http://www.w3.org/1999/xhtml" > <head> < ...