Hystrix有两个请求命令 HystrixCommand、HystrixObservableCommand。

  HystrixCommand用在依赖服务返回单个操作结果的时候。又两种执行方式

    -execute():同步执行。从依赖的服务返回一个单一的结果对象,或是在发生错误的时候抛出异常。

    -queue();异步执行。直接返回一个Future对象,其中包含了服务执行结束时要返回的单一结果对象。

    

  HystrixObservableCommand 用在依赖服务返回多个操作结果的时候。它也实现了两种执行方式

    -observe():返回Obervable对象,他代表了操作的多个结果,他是一个HotObservable

    -toObservable():同样返回Observable对象,也代表了操作多个结果,但它返回的是一个Cold Observable。

HystrixCommand:

使用方式一:继承的方式

package org.hope.hystrix.example;

import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixCommandKey;
import com.netflix.hystrix.HystrixRequestCache;
import com.netflix.hystrix.strategy.concurrency.HystrixConcurrencyStrategyDefault;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.client.RestTemplate; /**
* Created by lisen on 2017/12/15.
* HystrixCommand用在命令服务返回单个操作结果的时候
*/
public class CommandHelloWorld extends HystrixCommand<String> {
private final String name; public CommandHelloWorld(String name) {
super(HystrixCommandGroupKey.Factory.asKey("ExampleGroup"));
this.name = name;
} @Override
protected String run() throws Exception {
int i = 1/0;
return "Hello " + name + "!";
} /**
* 降级。Hystrix会在run()执行过程中出现错误、超时、线程池拒绝、断路器熔断等情况时,
* 执行getFallBack()方法内的逻辑
*/
@Override
protected String getFallback() {
return "faild";
}
}

单元测试:

package org.hope.hystrix.example;

import org.junit.Test;
import rx.Observable;
import rx.Observer;
import rx.Subscription;
import rx.functions.Action1; import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future; import static org.junit.Assert.assertEquals; /**
* Created by lisen on 2017/12/15.
*
*/
public class CommandHelloWorldTest { /**
* 测试同步执行
*/
@Test
public void testSynchronous() {
System.out.println(new CommandHelloWorld("World").execute());
} /**
* 测试异步执行
*/
@Test
public void testAsynchronous() throws ExecutionException, InterruptedException {
Future<String> fWorld = new CommandHelloWorld("World").queue();
System.out.println(fWorld.get()); //一步执行用get()来获取结果
} /**
* 虽然HystrixCommand具备了observe()和toObservable()的功能,但是它的实现有一定的局限性,
* 它返回的Observable只能发射一次数据,所以Hystrix还提供了HystrixObservableCommand,
* 通过它实现的命令可以获取能发多次的Observable
*/
@Test
public void testObserve() {
/**
* 返回的是Hot Observable,HotObservable,不论 “事件源” 是否有“订阅者”
* 都会在创建后对事件进行发布。所以对于Hot Observable的每一个“订阅者”都有
* 可能从“事件源”的中途开始的,并可能只是看到了整个操作的局部过程
*/
//blocking
Observable<String> ho = new CommandHelloWorld("World").observe();
// System.out.println(ho.toBlocking().single()); //non-blockking
//- this is a verbose anonymous inner-class approach and doesn't do assertions
ho.subscribe(new Observer<String>() {
@Override
public void onCompleted() {
System.out.println("==============onCompleted");
} @Override
public void onError(Throwable e) {
e.printStackTrace();
} @Override
public void onNext(String s) {
System.out.println("=========onNext: " + s);
}
}); ho.subscribe(new Action1<String>() {
@Override
public void call(String s) {
System.out.println("==================call:" + s);
}
});
} @Test
public void testToObservable() {
/**
* Cold Observable在没有 “订阅者” 的时候并不会发布时间,
* 而是进行等待,知道有 “订阅者” 之后才发布事件,所以对于
* Cold Observable的订阅者,它可以保证从一开始看到整个操作的全部过程。
*/
Observable<String> co = new CommandHelloWorld("World").toObservable();
System.out.println(co.toBlocking().single());
} }

使用方式二:注解的方式;

package org.hope.hystrix.example.service;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.ObservableExecutionMode;
import com.netflix.hystrix.contrib.javanica.command.AsyncResult;
import org.springframework.stereotype.Service;
import rx.Observable;
import rx.Subscriber; import java.util.concurrent.Future; /**
* 用@HystrixCommand的方式来实现
*/
@Service
public class UserService {
/**
* 同步的方式。
* fallbackMethod定义降级
*/
@HystrixCommand(fallbackMethod = "helloFallback")
public String getUserId(String name) {
int i = 1/0; //此处抛异常,测试服务降级
return "你好:" + name;
} public String helloFallback(String name) {
return "error";
} //异步的执行
@HystrixCommand(fallbackMethod = "getUserNameError")
public Future<String> getUserName(final Long id) {
return new AsyncResult<String>() {
@Override
public String invoke() {
int i = 1/0;//此处抛异常,测试服务降级
return "小明:" + id;
}
};
} public String getUserNameError(Long id) {
return "faile";
}
}

单元测试:

package org.hope.hystrix.example.service;

import javafx.application.Application;
import org.hope.hystrix.example.HystrixApplication;
import org.hope.hystrix.example.model.User;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.util.concurrent.ExecutionException; @RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = HystrixApplication.class)
public class UserServiceTest { @Autowired
private UserService userService; /**
* 测试同步
*/
@Test
public void testGetUserId() {
System.out.println("=================" + userService.getUserId("lisi"));
} /**
* 测试异步
*/
@Test
public void testGetUserName() throws ExecutionException, InterruptedException {
System.out.println("=================" + userService.getUserName(30L).get());
}
}

HystrixObservableCommand:

使用方式一:继承的方式

  HystrixObservable通过实现 protected Observable<String> construct() 方法来执行逻辑。通过 重写 resumeWithFallback方法来实现服务降级

package org.hope.hystrix.example;

import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixObservableCommand;
import rx.Observable;
import rx.Subscriber;
import rx.schedulers.Schedulers; public class ObservableCommandHelloWorld extends HystrixObservableCommand<String> { private final String name; public ObservableCommandHelloWorld(String name) {
super(HystrixCommandGroupKey.Factory.asKey("ExampleGroup"));
this.name = name;
} @Override
protected Observable<String> construct() {
return Observable.create(new Observable.OnSubscribe<String>() {
@Override
public void call(Subscriber<? super String> subscriber) {
try {
if(!subscriber.isUnsubscribed()) {
subscriber.onNext("Hello");
int i = 1 / 0; //模拟异常
subscriber.onNext(name + "!");
subscriber.onCompleted();
}
} catch (Exception e) {
subscriber.onError(e);
}
}
}).subscribeOn(Schedulers.io());
} /**
* 服务降级
*/
@Override
protected Observable<String> resumeWithFallback() {
return Observable.create(new Observable.OnSubscribe<String>() {
@Override
public void call(Subscriber<? super String> subscriber) {
try {
if (!subscriber.isUnsubscribed()) {
subscriber.onNext("失败了!");
subscriber.onNext("找大神来排查一下吧!");
subscriber.onCompleted();
}
} catch (Exception e) {
subscriber.onError(e);
}
}
}).subscribeOn(Schedulers.io());
}
}

单元测试:

package org.hope.hystrix.example;

import org.junit.Test;
import rx.Observable; import java.util.Iterator; public class ObservableCommandHelloWorldTest { @Test
public void testObservable() {
Observable<String> observable= new ObservableCommandHelloWorld("World").observe(); Iterator<String> iterator = observable.toBlocking().getIterator();
while(iterator.hasNext()) {
System.out.println(iterator.next());
}
} @Test
public void testToObservable() {
Observable<String> observable= new ObservableCommandHelloWorld("World").observe();
Iterator<String> iterator = observable.toBlocking().getIterator();
while(iterator.hasNext()) {
System.out.println(iterator.next());
}
} }

使用方式二:注解的方式;

package org.hope.hystrix.example.service;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.ObservableExecutionMode;
import org.springframework.stereotype.Service;
import rx.Observable;
import rx.Subscriber; @Service
public class ObservableUserService {
/**
* EAGER参数表示使用observe()方式执行
*/
@HystrixCommand(observableExecutionMode = ObservableExecutionMode.EAGER, fallbackMethod = "observFailed") //使用observe()执行方式
public Observable<String> getUserById(final Long id) {
return Observable.create(new Observable.OnSubscribe<String>() {
@Override
public void call(Subscriber<? super String> subscriber) {
try {
if(!subscriber.isUnsubscribed()) {
subscriber.onNext("张三的ID:");
int i = 1 / 0; //抛异常,模拟服务降级
subscriber.onNext(String.valueOf(id));
subscriber.onCompleted();
}
} catch (Exception e) {
subscriber.onError(e);
}
}
});
} private String observFailed(Long id) {
return "observFailed---->" + id;
} /**
* LAZY参数表示使用toObservable()方式执行
*/
@HystrixCommand(observableExecutionMode = ObservableExecutionMode.LAZY, fallbackMethod = "toObserbableError") //表示使用toObservable()执行方式
public Observable<String> getUserByName(final String name) {
return Observable.create(new Observable.OnSubscribe<String>() {
@Override
public void call(Subscriber<? super String> subscriber) {
try {
if(!subscriber.isUnsubscribed()) {
subscriber.onNext("找到");
subscriber.onNext(name);
int i = 1/0; ////抛异常,模拟服务降级
subscriber.onNext("了");
subscriber.onCompleted();
}
} catch (Exception e) {
subscriber.onError(e);
}
}
});
} private String toObserbableError(String name) {
return "toObserbableError--->" + name;
} }

单元测试:

package org.hope.hystrix.example.service;

import org.hope.hystrix.example.HystrixApplication;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.util.Iterator; @RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = HystrixApplication.class)
public class ObservableUserServiceTest { @Autowired
private ObservableUserService observableUserService; @Test
public void testObserve() {
Iterator<String> iterator = observableUserService.getUserById(30L).toBlocking().getIterator();
while(iterator.hasNext()) {
System.out.println("===============" + iterator.next());
}
} @Test
public void testToObservable() {
Iterator<String> iterator = observableUserService.getUserByName("王五").toBlocking().getIterator();
while(iterator.hasNext()) {
System.out.println("===============" + iterator.next());
}
}
}

总结:

  在实际使用时,我们需要为大多数执行过程中可能会失败的Hystrix命令实现服务降级逻辑,但是也有一些情况可以不去实现降级逻辑,比如:

  执行写操作的命令:

  执行批处理或离线计算的命令:

https://gitee.com/huayicompany/Hystrix-learn/tree/master/hystrix-example

参考:

[1]Github,https://github.com/Netflix/Hystrix/wiki/How-it-Works

[2] 《SpringCloud微服务实战》,电子工业出版社,翟永超

Hystrix请求命令 HystrixCommand、HystrixObservableCommand的更多相关文章

  1. SpringCloud实战-Hystrix请求熔断与服务降级

    我们知道大量请求会阻塞在Tomcat服务器上,影响其它整个服务.在复杂的分布式架构的应用程序有很多的依赖,都会不可避免地在某些时候失败.高并发的依赖失败时如果没有隔离措施,当前应用服务就有被拖垮的风险 ...

  2. Spring-cloud (八) Hystrix 请求缓存的使用

    前言: 最近忙着微服务项目的开发,脱更了半个月多,今天项目的初版已经完成,所以打算继续我们的微服务学习,由于Hystrix这一块东西好多,只好多拆分几篇文章写,对于一般对性能要求不是很高的项目中,可以 ...

  3. Spring-cloud (九) Hystrix请求合并的使用

    前言: 承接上一篇文章,两文本来可以一起写的,但是发现RestTemplate使用普通的调用返回包装类型会出现一些问题,也正是这个问题,两文没有合成一文,本文篇幅不会太长,会说一下使用和适应的场景. ...

  4. Hystrix请求熔断与服务降级

    Hystrix请求熔断与服务降级 https://www.cnblogs.com/huangjuncong/p/9026949.html SpringCloud实战-Hystrix请求熔断与服务降级 ...

  5. SpringCloud学习之Hystrix请求熔断与服务降级(六)

    我们知道大量请求会阻塞在Tomcat服务器上,影响其它整个服务.在复杂的分布式架构的应用程序有很多的依赖,都会不可避免地在某些时候失败.高并发的依赖失败时如果没有隔离措施,当前应用服务就有被拖垮的风险 ...

  6. USB设备请求命令详解

    USB设备请求命令 :bmRequestType + bRequest + wValue + wIndex + wLength 编号 值  名称 (0) 0  GET_STATUS:用来返回特定接收者 ...

  7. USB设备描述符和请求命令

    USB设备描述符和请求命令 介绍标准的USB设备描述符和请求命令. 标准的USB描述符 当USB设备第一次连接到主机上时,要接收主机的枚举和配置,目的就是让主机知道该设备具有什么功能.是哪一类的USB ...

  8. 【Redis】集群请求命令处理

    集群请求命令处理 在Redis的命令处理函数processCommand(server.c)中有对集群节点的处理,满足以下条件时进入集群节点处理逻辑中: 启用了集群模式,通过server.cluste ...

  9. 笔记:Spring Cloud Hystrix 封装命令

    使用继承的方式来创建Hystrix 命令,不是用注解的方式来使用 Hystrix 创建 HelloGetCommand 对象,继承与 HystrixCommand 并实现 run 方法,示例如下: p ...

随机推荐

  1. Qt Creator简单计算器的Demo

    小编在期末数据结构课设中遇到要做可视化界面的问题,特意去学习了一下Qt的用法,今天就来给大家分享一下. 我用的是Qt5.80,当然这只是一个简易的计算器Demo,,请大家勿喷. 首先我创建了一个Qt ...

  2. Hadoop源码篇--Client源码

    一.前述 今天起剖析源码,先从Client看起,因为Client在MapReduce的过程中承担了很多重要的角色. 二.MapReduce框架主类 代码如下: public static void m ...

  3. SuperSocket入门(四)-命令行协议

         前面已经了解了supersocket的一些基本的属性及相关的方法,下面就进入重点的学习内容,通信协议.在没有看官方的文档之前,对于协议的理解首先想到的是TCP和UDP协议.TCP 和 UDP ...

  4. MySQL使用存储过程代替子查询

    摘要: 出处:黑洞中的奇点 的博客 http://www.cnblogs.com/kelvin19840813/ 您的支持是对博主最大的鼓励,感谢您的认真阅读.本文版权归作者所有,欢迎转载,但请保留该 ...

  5. iOS 应用全部添加滑动返回

    if ([self  class] == [HomeViewController class]||[self  class] == [ComprehensivefinanceViewControlle ...

  6. 针对Oracle的审计方案

    主题:针对Oracle的审计方案 数据库环境:Oracle 11g 数据库审计需求: 1.需要对连接数据库的行为进行审计 2.需要对核心表的DML操作进行审计 3.需要迁移审计数据到指定表空间 4.需 ...

  7. Echarts---柱状图实现

    做Echarts很简单,可以参看官网 http://echarts.baidu.com/index.html 作为程序员我们只需要把静态数据替换成我们自己需要的! 下面看一个自己做的例子: 还是先看看 ...

  8. eclipse安装java web插件

    1 查看eclipse版本 找到eclipse的安装目录,找到readme文件,打开其中的html文件,我的是4.6版本的,代号是oxygen 2 安装 打开eclipse,点击help-Instal ...

  9. ajax中url赋json格式的值时发生中文乱码的相关问题

    具体流程:转入到jsp界面时会加载ajax,ajax转到url时传带hide在jsp界面的值titleString,其来源见下面的代码. String title=new String("\ ...

  10. python写一个DDos脚本(DOS)

    前言:突然想写,然后去了解原理 DDOS原理:往指定的IP发送数据包(僵尸网络),导致服务器 拒绝服务,无法正常访问. 0x01: 要用到的模块 scapy模块 pip install scapy 或 ...