【Hystrix系列】二、RxJava的调用栈分析

来源:互联网 发布:淘宝游戏店铺转让 编辑:程序博客网 时间:2024/06/06 03:29

Netflix开源了Hystrix作为熔断限流的利器,在IT圈备受赞誉,也是Spring Cloud的标准组件。在Hystrix中使用的重点是Java的并发包concurrent和Rxjava。其中RxJava是响应式程序设计的一种实现,以观察者模式为蓝本。在响应式程序设计中,当数据到达的时候,消费者做出响应。响应式编程可以将事件传递给注册了的 observer。

在网上的绝大多数案例要么是对Hystrix的wiki的翻译(Netflix的文档写的确实经典,图文并茂),要么是简单的代码实现。如果你打开源代码,就会发现Hystrix中使用了大量的RxJava,想要正常的跟踪单步调试,完全找不到北。

一步我们要看一下执行最简单的Hystrix的Command的堆栈情况和调用的时序图。创建一个最简单的HelloCommand,因为需要调试,因此我选择使用信号量隔离机制,同时设置一个超时时间,以便我能抓取一个调用栈的截屏。

package com.travel.hystrix;import com.netflix.hystrix.HystrixCommand;import com.netflix.hystrix.HystrixCommandGroupKey;import com.netflix.hystrix.HystrixCommandProperties;public class HelloCommand extends HystrixCommand<Boolean>{protected HelloCommand() {super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("HelloCommand")).andCommandPropertiesDefaults(HystrixCommandProperties.Setter().withExecutionIsolationStrategy(HystrixCommandProperties.ExecutionIsolationStrategy.SEMAPHORE) //设置使用信号量隔离策略                .withExecutionTimeoutInMilliseconds(100000000)                ));}@Overrideprotected Boolean run() throws Exception {Thread.sleep(1000);System.out.println("HelloCommand finished.");return true;}}

然后就是调用的JUnit代码

package com.travel.hystrix;import org.junit.Test;public class HelloCommandTest {@Testpublic void test(){System.out.println("HelloCommand test begin.");HelloCommand cmd = new HelloCommand();try{cmd.execute();}catch(Exception ex){ex.printStackTrace();}finally{System.out.println("HelloCommand test byebye.");}}}

然后就是调试代码,在run方法上设置一个断点。没有看错,我一共截了三屏。




为了更加形象地描述调用关系,咱们上个时序图。

总结一下,为啥Hystrix搞得调用层次这么深,因为它是框架要控制超时,另外需要处理异常响应。不过这么多深的层次,你需要慎重使用Hystrix,尤其是高并发、重负载的场景上。


原创粉丝点击