1. 依赖引入

pom.xml

<properties>
    <hystrix-version>1.4.22</hystrix-version>
</properties>
<dependencies>
    <dependency>
        <groupId>com.netflix.hystrix</groupId>
        <artifactId>hystrix-core</artifactId>
        <version>${hystrix-version}</version>
    </dependency>
    <dependency>
        <groupId>com.netflix.hystrix</groupId>
        <artifactId>hystrix-metrics-event-stream</artifactId>
        <version>${hystrix-version}</version>
    </dependency>
    <dependency>
        <groupId>com.netflix.hystrix</groupId>
        <artifactId>hystrix-javanica</artifactId>
        <version>${hystrix-version}</version>
    </dependency>
    <dependency>
        <groupId>com.netflix.hystrix</groupId>
        <artifactId>hystrix-servo-metrics-publisher</artifactId>
        <version>${hystrix-version}</version>
    </dependency>
 
 
</dependencies>

applicationContext.xml:

<aop:aspectj-autoproxy/>
<bean
id=
"hystrixAspect" class="com.netflix.hystrix.contrib.javanica.aop.aspectj.HystrixCommandAspect"/>

web.xml:

<servlet>
    <display-name>HystrixMetricsStreamServlet</display-name>
    <servlet-name>HystrixMetricsStreamServlet</servlet-name>
    <servlet-class>com.netflix.hystrix.contrib.metrics.eventstream.HystrixMetricsStreamServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>HystrixMetricsStreamServlet</servlet-name>
    <url-pattern>/hystrix.stream</url-pattern>
</servlet-mapping>

jmonitor:

collector=jvm,appdata,http

2. 使用

这里只讲注解的使用方式以及比较重要的部分,如果需要了解全部查看:https://github.com/Netflix/Hystrix/wiki/How-To-Use

2.1 Hystrix command

2.1.1 同步执行

public class UserService
{
...
    @HystrixCommand
    public User
getUserById(String id) {
        return userResource.getUserById(id);
    }
}

2.1.2 异步执行

public class UserService
{
...
 
  @HystrixCommand
    public Future<User>
getUserByIdAsync(
final String
id) {
        return new AsyncResult<User>()
{
            @Override
            public User
invoke() {
                return userResource.getUserById(id);
            }
        };
    }
}

2.1.3 反应执行()

public class UserService
{

    ...
 
  @HystrixCommand
    public Observable<User>
getUserById(
final String
id) {
        return Observable.create(new Observable.OnSubscribe<User>()
{
                @Override
                public void call(Subscriber<? super User>
observer) {
                    try {
                        if (!observer.isUnsubscribed())
{
                            observer.onNext(userResource.getUserById(id));
                            observer.onCompleted();
                        }
                    catch (Exception
e) {
                        observer.onError(e);
                    }
                }
            });
    }
}

2.1.4 三种模式使用区别

  • 同步执行:当执行到注解方法时,程序会顺序执行。
  • 异步执行:当执行到注解方法时,会并发异步执行,返回一个Future对象,后面使用.get()方法来阻塞拿到结果。如果有多个方法时,执行时间就是其中最长的一个服务的执行时间。
  • 反应执行:当执行到注解方法时,返回一个观察者。支持EAGER和LAZY模式。和同步异步执行的区别是,当对多个方法之间的返回结果不需要做合并而是希望当多个方法返回时触发一些事件时比较适合使用该模式。

反应执行没太明白,如果需要了解可以先参考下这个https://mcxiaoke.gitbooks.io/rxdocs/content/Intro.html

2.2 Fallback

@HystrixCommand(fallbackMethod
"fallback1")
User
getUserById(String id) {
    throw new RuntimeException("getUserById
command failed"
);
}
 
@HystrixCommand(fallbackMethod
"fallback2")
User
fallback1(String id, Throwable e) {
    assert "getUserById
command failed"
.equals(e.getMessage());
    throw new RuntimeException("fallback1
failed"
);
}
 
@HystrixCommand(fallbackMethod
"fallback3")
User
fallback2(String id) {
    throw new RuntimeException("fallback2
failed"
);
}

注意点:

  • fallback应该和注解方法在同一类下
  • fallback的返回值和参数列表应该和注解方法一致,如果需要异常,则在末尾添加Throwable参数,对访问修饰符无要求
  • fallback方法上可以继续添加fallback

command和fallback只支持以下几种组合:

  • sync command, sync fallback
  • async command, sync fallback
  • async command, async fallback

2.3 Error Propagation

@HystrixCommand(ignoreExceptions
= {BadRequestException.
class})
    public User
getUserById(String id) {
        return userResource.getUserById(id);
    }

当遇到BadRequestException时不会进入fallback,而是直接抛出异常

2.4 Configuration

@HystrixCommand(groupKey="UserGroup",
commandKey = 
"GetUserByIdCommand"
                commandProperties
= {
                        @HystrixProperty(name
"execution.isolation.thread.timeoutInMilliseconds",
value = 
"500")
                },
                threadPoolProperties
= {
                        @HystrixProperty(name
"coreSize",
value = 
"30"),
                        @HystrixProperty(name
"maxQueueSize",
value = 
"101"),
                        @HystrixProperty(name
"keepAliveTimeMinutes",
value = 
"2"),
                        @HystrixProperty(name
"queueSizeRejectionThreshold",
value = 
"15"),
                        @HystrixProperty(name
"metrics.rollingStats.numBuckets",
value = 
"12"),
                        @HystrixProperty(name
"metrics.rollingStats.timeInMilliseconds",
value = 
"1440")
        })
参数
作用
备注

groupKey

表示所属的group,一个group共用线程池

默认值:getClass().getSimpleName();

commandKey

  默认值:当前执行方法名

execution.isolation.strategy

隔离策略,有THREAD和SEMAPHORE

默认使用THREAD模式,以下几种可以使用SEMAPHORE模式:

  • 只想控制并发度
  • 外部的方法已经做了线程隔离
  • 调用的是本地方法或者可靠度非常高、耗时特别小的方法(如medis)

execution.isolation.thread.timeoutInMilliseconds

超时时间

默认值:1000

在THREAD模式下,达到超时时间,可以中断

在SEMAPHORE模式下,会等待执行完成后,再去判断是否超时

设置标准:

有retry,99meantime+avg meantime

没有retry,99.5meantime

execution.timeout.enabled

是否打开超时  

execution.isolation.thread.interruptOnTimeout

是否打开超时线程中断 THREAD模式有效

execution.isolation.semaphore.maxConcurrentRequests

信号量最大并发度 SEMAPHORE模式有效,默认值:10

fallback.isolation.semaphore.maxConcurrentRequests

fallback最大并发度 默认值:10

circuitBreaker.requestVolumeThreshold

熔断触发的最小个数/10s 默认值:20

circuitBreaker.sleepWindowInMilliseconds

熔断多少秒后去尝试请求 默认值:5000

circuitBreaker.errorThresholdPercentage

失败率达到多少百分比后熔断

默认值:50

主要根据依赖重要性进行调整

circuitBreaker.forceClosed

是否强制关闭熔断 如果是强依赖,应该设置为true

coreSize

线程池coreSize

默认值:10

设置标准:qps*99meantime+breathing room

maxQueueSize

请求等待队列

默认值:-1

如果使用正数,队列将从SynchronizeQueue改为LinkedBlockingQueue

转自:http://blog.csdn.net/zheng0518/article/details/51713900

Hystrix使用Commond的三种方式的更多相关文章

  1. 监视EntityFramework中的sql流转你需要知道的三种方式Log,SqlServerProfile, EFProfile

    大家在学习entityframework的时候,都知道那linq写的叫一个爽,再也不用区分不同RDMS的sql版本差异了,但是呢,高效率带来了差灵活性,我们 无法控制sql的生成策略,所以必须不要让自 ...

  2. iOS字体加载三种方式

    静态加载 动态加载 动态下载苹果提供的多种字体 其他 打印出当前所有可用的字体 检查某字体是否已经下载 这是一篇很简短的文章,介绍了 iOS 自定义字体加载的三种方式. 静态加载 这个可以说是最简单最 ...

  3. 0036 Java学习笔记-多线程-创建线程的三种方式

    创建线程 创建线程的三种方式: 继承java.lang.Thread 实现java.lang.Runnable接口 实现java.util.concurrent.Callable接口 所有的线程对象都 ...

  4. 【整理】Linux下中文检索引擎coreseek4安装,以及PHP使用sphinx的三种方式(sphinxapi,sphinx的php扩展,SphinxSe作为mysql存储引擎)

          一,软件准备 coreseek4.1 (包含coreseek测试版和mmseg最新版本,以及测试数据包[内置中文分词与搜索.单字切分.mysql数据源.python数据源.RT实时索引等测 ...

  5. JDBC的批处理操作三种方式 pstmt.addBatch()

    package lavasoft.jdbctest; import lavasoft.common.DBToolkit; import java.sql.Connection; import java ...

  6. 【Java EE 学习 52】【Spring学习第四天】【Spring与JDBC】【JdbcTemplate创建的三种方式】【Spring事务管理】【事务中使用dbutils则回滚失败!!!??】

    一.JDBC编程特点 静态代码+动态变量=JDBC编程. 静态代码:比如所有的数据库连接池 都实现了DataSource接口,都实现了Connection接口. 动态变量:用户名.密码.连接的数据库. ...

  7. Java设置session超时(失效)的三种方式

    1. 在web容器中设置(此处以tomcat为例) 在tomcat-6.0\conf\web.xml中设置,以下是tomcat 6.0中的默认配置: <!-- ================= ...

  8. angularjs 自定义服务的三种方式

    angularjs 中可通过三种($provider,$factory,$service)方式自定义服务,以下是不同的实现形式: // 定义module , module中注入$providevar ...

  9. 【转】Apache 配置虚拟主机三种方式

    Apache 配置虚拟主机三种方式  原文博客http://www.cnblogs.com/hi-bazinga/archive/2012/04/23/2466605.html 一.基于IP 1. 假 ...

随机推荐

  1. 如何查找python安装包的路径site-packages?

    使用命令: python -m site python -m site --user-site 注意当查看指定版本的python的安装包时,需要指定python版本,比如python2.7.15 -m ...

  2. 从头開始学 RecyclerView(六) LayoutManager

    前言 在前面的文章中.每一个演示样例,都使用了LayoutManager,毕竟它是RecyclerView必不可少的一部分. LayoutManager,顾名思义,就是『布局管理器』. 使用例如以下代 ...

  3. Eclipse中在android项目中出现新建一个Activity后,出现整个project的报错以及包导入以后无法执行等等情况分析。

    今天用Eclipse去写android项目,然后后面须要建一个Blank  Activity后,非常正常的建立的.然后那个Activity是基于ActionBarAtivity,要导入v7,结果由于这 ...

  4. csm pssm +pcf pcss sdsm

    这几个shadow算法 pcf是sample时候用的 按照一个mode采样几个位置 根据采样结果 决定0-1  可以是0.234 这样就不是 0或者1 就是soft了 主要讲下pcss 是啥 因为我之 ...

  5. 使用jQuery通过点击它删除HTML表格行-超简单

    jQuery的已成为所有时刻的最常用和最喜爱的JavaScript框架之一.它不仅不会减少在JavaScript编码简单的技术开销,而且也使您的代码的跨浏览器兼容.我已经写了许多关于jQuery教程, ...

  6. EasyUI-EasyUI框架入门学习

    前言 新项目的开发前端技术打算采用EasyUI框架(基于EasyUI较为丰富的UI组件库),项目组长将前端EasyUI这块的任务分配给了我.在进行开发之前,需要我这菜鸟对EasyUI框架进行一些基础的 ...

  7. C经典之9-system,if,do,while---ShinePans

    #include <stdio.h> #include <conio.h> #include <stdlib.h> //system(); 这个指令须要用到此头文件 ...

  8. python xlrd简单读取excel

    import xlrd #打开文件 book = xlrd.open_workbook ('Status.xlsx') #获取数据表 table1 = book.sheets()[0] table2 ...

  9. 免费资源:Bootstrap开发的创意模板

    在线演示 免费下载 一套免费的Bootstrap网站模板,使用现代的布局并支持响应式.拥有非常棒的CSS3动画效果及其滚动效果.

  10. 001-Cocos2dx-2.1.3环境搭建-windows

    图片丢失,转到:http://blog.csdn.net/whyhowwhat/article/details/51908229