在微服务架构中, 存在着那么多的服务单元, 若一个单元出现故障, 就很容易因依赖关系而引发故障的蔓延,最终导致整个系统的瘫痪,这样的架构相较传统架构更加不稳定。为了解决这样的问题, 产生了断路器等一系列的服务保护机制

  Spring Cloud Hystrix实现了断路器、 线程隔离等一系列服务保护功能。它也是基于Netflix的开源框架Hystrix实现的, 该框架的目标在于通过控制那些访问远程系统、 服务和第三方库的节点, 从而对延迟和故障提供更强大的容错能力。Hystrix具备服务降级、 服务熔断、 线程和信号隔离、 请求缓存、 请求合并以及服务监控等强大功能

快速入门

先部署按照以上架构图一些服务:

  • eureka-server工程: 服务注册中心, 端口为1111
  • hello-service工程: HELLO-SERVICE的服务单元, 两个实例启动端口分别为8081和 8082
  • ribbon-consume工程:使用Ribbon 实现的服务消费者, 端口为9000

在未加入断路器之前, 关闭8081的实例, 发送GET请求到http://localhost:9000/ribbon-consumer, 可以获得输出,接下来开始引入Spring Cloud Hystrix

在ribbon-consumer工程的pom.xml的dependency节点中引入springcloud-starter-hystrix依赖:

 <dependency>
  <groupid>org.springframework.cloud</groupid>
  <artifactid>spring-cloud-starter-hystrix</artifactid>
</dependency>

在ribbon-consumer工程的主类ConsumerApplication中使用@Enable­-CircuitBreaker注解开启断路器功能:

  @EnableCircuitBreaker
@EnableDiscoveryClient
@SpringBootApplication
4 public class ConsumerApplication {
@Bean
6 @LoadBalanced
7 RestTemplate restTemplate() {
8   return new RestTemplate();
9 }
10 public static void main(String[) args) {
11   SpringApplication.run(ConsumerApplication.class, args)
12 }
13 }

注意:这里还可以使用 Spring Cloud 应用中的@SpringCloudApplication 注解来修饰应用主类, 该注解的具体定义如下所示。 可以看到, 该注解中包含了上述我们所引用的三个注解, 这也意味着—个 Spring Cloud 标准应用应包含服务发现以及断路器

 @Target ({ ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootApplication
@EnableDiscoveryClient
@EnableCircuitBreaker
public interface SpringCloudApplication {
}

改造服务消费方式, 新增 HelloService 类, 注入 RestTemplate 实例。 然后,将在 ConsumerController中对 RestTemplate 的使用迁移到 helloService函数中, 最后, 在 helloService 函数上增加@HystrixCornrnand 注解来指定回调方法:

 @Service
2 public class HelloService {
3   @Autowired
4   RestTemplate restTemplate;
5   @HystrixCommand(fallbackMethod = "helloFallback")
6   public String helloService() {
7     return restTemplate.getForEntity("http://HELLO-SERVICE/hello", String.class).getBody();
9   }
10   public String helloFallback () (
11     return "error";
12   }
13 }

修改 ConsumerController 类, 注入上面实现的 HelloService 实例, 并在helloConsumer 中进行调用:

1 @RestController
2 public class ConsumerController {
3   @Autowired
4   HelloService helloService;
5   @RequestMapping(value = "/ribbon-consumer", method= RequestMethod.GET)
6   public String helloConsumer () {
7     return helloService.helloService();
8   }
9 }

重新启动之前关闭的 8081 端口的 Hello-Service, 确保此时服务注册中心、 两个 Hello-Service 以及 RIBBONCONSUMER 均已启动,访问 http://localhost:9000/ribbon-consumer 可以轮询两个 HELLO-SERV工CE 并返回一些文字信息。 此时我们继续断开 8081 的 HELLO-SERVICE,然后访问 http://localhost:9000/ribbon-consumer, 当轮询到 8081 服务端时,输出内容为 error, 不再是之前的错误内容,Hystrix 的服务回调生效。除了通过断开具体的服务实例来模拟某个节点无法访问的情况之外, 我们还可以模拟一下服务阻塞(长时间未响应)的情况。 我们对 HELLO-SERVICE 的/hello 接口做一些修改

 1 @RequestMapping(value = "/hello", method= RequestMethod.GET)
2 public String hello() throws Exception {
3   Serviceinstance instance= client.getLocalServiceinstance();
4   //让处理线程等待几秒钟
5   int sleepTime = new Random() . nextint (3000);
6   logger.info("sleepTime:" + sleepTime);
7   Thread.sleep{sleepTime);
8   logger.info("/hello, host:" + instance.getHost() + ", service id:" +
9   instance.getServiceid());
10   return "Hello World";
11 }
}

通过 Thread. sleep ()函数可让/hello 接口的处理线程不是马上返回内容,而是在阻塞几秒之后才返回内容。 由于 Hystrix 默认超时时间为 2000 毫秒, 所以这里采用了 0至3000 的随机数以让处理过程有一定概率发生超时来触发断路器。为了更精准地观察断路器
的触发,在消费者调用函数中做一些时间记录,具体如下:

 @HystrixCommand(fallbackMethod = "helloFallback", commandKey = "helloKey")
2 public spring hello() {
3 long start = System.currentTimeMillis();
4 //消费服务的逻辑
5 ···
6 long end= System.currentTimeMillis();
7 logger.info("Spend time : "+ (end - start));
8 return result.toString();
9 }

重新启动HELLO-SERVICE和RIBBON-CONSUMER的实例,连续访问http://localhost:9000/ribbon-consumer几次,我们可以观察到,当RIBBON-CONSUMER的控制台中输出的Spend time大于2000的时候,就会返回error, 即 服务消费者因调用的服务超时从而触发熔断请求, 并调用回调逻辑返回结果

第五章 服务容错保护: Spring Cloud Hystrix的更多相关文章

  1. 第五章 服务容错保护:Spring Cloud Hystrix

    在微服务架构中,我们将系统拆分为很多个服务,各个服务之间通过注册与订阅的方式相互依赖,由于各个服务都是在各自的进程中运行,就有可能由于网络原因或者服务自身的问题导致调用故障或延迟,随着服务的积压,可能 ...

  2. SpringCloud---服务容错保护---Spring Cloud Hystrix

    1.概述 1.1 在分布式架构中,存在着许多的服务单元,若一个单元出现故障,很容易因依赖关系引发故障的蔓延,最终导致整个系统的瘫痪: 为了解决这样的问题,产生了断路器等服务保护机制: 1.2 分布式架 ...

  3. SpringCloud开发学习总结(五)—— 服务容错保护Hystrix

    在微服务架构中,我们将系统拆分成了很多服务单元,各单元的应用间通过服务注册与订阅的方式相互依赖.但由于每个单元都在不同的进程中运行,一来通过远程调用的方式执行,这样就有可能因为网络原因或是依赖服务自身 ...

  4. 分布式系统的延时和故障容错之Spring Cloud Hystrix

    本示例主要介绍 Spring Cloud 系列中的 Eureka,如何使用Hystrix熔断器容错保护我们的应用程序. 在微服务架构中,系统被拆分成很多个服务单元,各个服务单元的应用通过 HTTP 相 ...

  5. 微服务架构之spring cloud hystrix&hystrix dashboard

    在前面介绍spring cloud feign中我们已经使用过hystrix,只是没有介绍,spring cloud hystrix在spring cloud中起到保护微服务的作用,不会让发生的异常无 ...

  6. 第三章 服务治理:Spring Cloud Eureka

    Spring Cloud Eureka是Spring Cloud Netflix 微服务套件中的一部分,它基于Netflix Eureka做了二次封装,主要负责完成微服务架构中的服务治理功能.Spri ...

  7. 第三章 服务治理: Spring Cloud Eureka

    Spring Cloud Eureka是 Spring Cloud Netflix微服务套件中的一部分,它基于Netflix Eureka做了二次封装,主要负责完成微服务架构中的服务治理功能 服务治理 ...

  8. Spring Cloud(四):服务容错保护 Hystrix【Finchley 版】

    Spring Cloud(四):服务容错保护 Hystrix[Finchley 版]  发表于 2018-04-15 |  更新于 2018-05-07 |  分布式系统中经常会出现某个基础服务不可用 ...

  9. 白话SpringCloud | 第五章:服务容错保护(Hystrix)

    前言 前一章节,我们知道了如何利用RestTemplate+Ribbon和Feign的方式进行服务的调用.在微服务架构中,一个服务可能会调用很多的其他微服务应用,虽然做了多集群部署,但可能还会存在诸如 ...

随机推荐

  1. ng-bind 拼接字符标签

  2. MongoDB 安装、运行、使用、数据恢复

     1.安装MongoDB社区版 # . 导入MongoDB public GPG Key sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com ...

  3. 单机ZooKeeper配置

    1.创建zoo.cfg copy D:\zookeeper3.4.6\conf\zoo_sample.cfg zoo.cfg 修改追加如下内容 dataDir=D:/zookeeper3.4.6/da ...

  4. SQL基础五(作业代码)

    create database stuinfo create table student ( mid ) not null primary key, mname ) not null ) create ...

  5. BZOJ4832: [Lydsy1704月赛]抵制克苏恩(记忆化&期望)

    Description 小Q同学现在沉迷炉石传说不能自拔.他发现一张名为克苏恩的牌很不公平.如果你不玩炉石传说,不必担心,小Q 同学会告诉你所有相关的细节.炉石传说是这样的一个游戏,每个玩家拥有一个 ...

  6. HihoCoder1164 随机斐波那契(概率DP)

    描述 大家对斐波那契数列想必都很熟悉: a0 = 1, a1 = 1, ai = ai-1 + ai-2,(i > 1). 现在考虑如下生成的斐波那契数列: a0 = 1, ai = aj + ...

  7. tensorflow图像基本处理

    tensorflow库提供的专门的图片处理库,以下只是部分示例,更多函数请参照源码'\tensorflow_api\v1\image__init__.py' 加载图像 方式1: 使用tf.gfile. ...

  8. LOJ2422 NOIP2015 斗地主 【搜索+贪心】*

    LOJ2422 NOIP2015 斗地主 LINK 题目大意很简单,就是问你斗地主的一分手牌最少多少次出完 然后我们发现对于一种手牌状态,不考虑顺子的情况是可以贪心做掉的 然后我们直接枚举一下顺子出牌 ...

  9. LOJ2500 NOIP2014 飞扬的小鸟 【背包DP】*

    LOJ2500 NOIP2014 飞扬的小鸟 LINK 题目大意就是说有n个柱子,在每一秒你可以选择不点下降高度y和点p次上升x∗p,若果当前位置加上x∗p大于上界m,就会停在m. 如果可以成功穿越所 ...

  10. 微软 Windows 系统检测网络连通性(用于显示感叹号)竟然是通过访问一个特殊网址来实现的

    一次我走到了弱网环境中,意外地发现浏览器打开了 http://www.msftconnecttest.com/redirect 网址,随后右下角的网络图标出现了一枚“感叹号”.   吹水的推断 从直观 ...