一 工作流程
本篇介绍工作流程的前三步。
二 创建HystrixCommand或HystrixObservableCommand对象
构建一个HystrixCommand或是HystrixObservableCommand对象,用来表示对依赖服务的操作请求,同时传递所有需要的参数。
这两个Command对象针对两种不同的场景:
-
HystrixCommand:用在依赖的服务返回单个操作结果的时候。
-
HystrixObservableCommand:用在依赖服务返回多个操作结果的时候。
三 命令执行
从图中,可以看到一共存在4种命令的执行方式,而Hystrix在执行的时候会根据创建的Command对象以及具体的情况来选择一个执行。
HystrixCommand实现了下面两个执行方式:
-
execute():同步执行,从依赖的服务返回一个单一的结果对象,或者是发生错误时抛出异常。
-
queue():异步执行,直接返回一个Future对象,其中包含了服务执行结果时要返回的单一结果对象。
举例:
R value=command.execute();
Future<R> fValue=command.queue();
HystrixObservableCommand实现了下面两个执行方式:
-
observer():返回Observable对象,它代表了操作的多个结果,它是一个Hot Observable。
-
toObervable():返回Observable对象,也代表了操作的多个结果,但它返回的是一个Cold Observable。
举例:
Observable<R> ohValue=command.observe();
Observable<R> ocValue=command.toObservable();
execute()和queue()的源码如下,从源码中,我们可以看到:最终它们都调用toObservable()方法
public R execute() {
try {
return queue().get();
} catch (Exception e) {
throw Exceptions.sneakyThrow(decomposeException(e));
}
}
public Future<R> queue() {
/*
* The Future returned by Observable.toBlocking().toFuture() does not implement the
* interruption of the execution thread when the "mayInterrupt" flag of Future.cancel(boolean) is set to true;
* thus, to comply with the contract of Future, we must wrap around it.
*/
final Future<R> delegate = toObservable().toBlocking().toFuture();
...
}
四 结果是否被缓存
若当前命令的请求缓存功能被启用,并且该命令缓存命中,那么缓存的结果会立即以Observerable对象形式返回。