博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
通过注解使用Hystrix
阅读量:4038 次
发布时间:2019-05-24

本文共 4616 字,大约阅读时间需要 15 分钟。

参考:https://github.com/Netflix/Hystrix/tree/master/hystrix-contrib/hystrix-javanica

Java语言比其他语言(如反射和注解)具有很大的优势。 所有现代框架,如Spring,Hibernate,myBatis等都力求最大限度地利用这一优势。 引入Hystrix注解的想法是改进的明显解决方案。 目前使用Hystrix涉及撰写大量的代码,这是快速开发的障碍。 您可能花费大量时间编写Hystrix命令。 通过引入支持注解,可以更容易的使用Hystrix。

通过在项目中对Hystrix的使用,总结出常用的如下几点:

一、使用HystrixCommand注解

1、同步执行
public class UserService {...    @HystrixCommand    public User getUserById(String id) {        return userResource.getUserById(id);    }}...
2、异步执行
@HystrixCommand    public Future
getUserByIdAsync(final String id) { return new AsyncResult
() { @Override public User invoke() { return userResource.getUserById(id); } }; }
3、响应执行--------这块我也不太了解,平常也用不到,貌似使用的rx包下Obervable类,在Android开发中用的比较平凡
@HystrixCommand    public Observable
getUserById(final String id) { return Observable.create(new Observable.OnSubscribe
() { @Override public void call(Subscriber
observer) { try { if (!observer.isUnsubscribed()) { observer.onNext(new User(id, name + id)); observer.onCompleted(); } } catch (Exception e) { observer.onError(e); } } }); }

二、使用注解配置相关属性

现在使用的配置大概有如下几种:
@HystrixCommand(groupKey = "hello",commandKey = "hello-service",threadPoolKey = "hello-pool",        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")        },        commandProperties = {        @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "5000"),        @HystrixProperty(name = "execution.isolation.strategy",value = "THREAD")},        fallbackMethod = "helloFallBack"        )
大部分场景下使用默认属性即可,不需要配置那么多属性,更多的属性可以参考:https://github.com/Netflix/Hystrix/wiki/Configuration
属性这么多紧接着就有一个问题:我们是否需要为每一个需要使用hystrix方法都定义一遍属性?
比如:
一个类中有很多方法,不能在每个方法都配置一遍相同的属性,容易造成配置代码的冗余;所以Javanica提供了
@DefaultProperties注解,解释如下:
@DefaultProperties是类(类型)级别的注释,允许默认命令属性,如groupKey,threadPoolKey,commandProperties,threadPoolProperties,ignoreExceptions和raiseHystrixExceptions。 
使用此注解指定的属性,将在类中使用@HystrixCommand注解的方法中公用
,除非某个方法明确使用相应的@HystrixCommand参数来指定这些属性。 
例:
@DefaultProperties(groupKey = "DefaultGroupKey")class Service {    @HystrixCommand // hystrix command group key is 'DefaultGroupKey'    public Object commandInheritsDefaultProperties() {        return null;    }    @HystrixCommand(groupKey = "SpecificGroupKey") // command overrides default group key    public Object commandOverridesGroupKey() {        return null;    }}

三、fallback方法,回退逻辑及异常

1、定义一个fallback方法需要注意以下几点:
(1)fallback方法必须和指定fallback方法的主方法在一个类中
(2)fallback方法的参数必须要和主方法的参数一致
否则不生效
(3)使用fallback方法需要根据依赖服务设置合理的超时时间,即
commandProperties = {@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "5000")}
如果不配置的话默认是1s,如果依赖服务的响应时间超过1s,则执行fallback;所以需要根据实际情况而定
2、可以在fallback方法中通过Throwable e参数获得主方法抛出的异常,例如:
@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");        }        @HystrixCommand(fallbackMethod = "staticFallback")        User fallback3(String id, Throwable e) {            assert "fallback2 failed".equals(e.getMessage());            throw new RuntimeException("fallback3 failed");        }        User staticFallback(String id, Throwable e) {            assert "fallback3 failed".equals(e.getMessage());            return new User("def", "def");        }                // test        @Test        public void test() {        assertEquals("def", getUserById("1").getName());        }

转载地址:http://pkjdi.baihongyu.com/

你可能感兴趣的文章
std::function 和 std::bind 的简单例子
查看>>
CFormView简介
查看>>
Visual Studio 2010 与 VC++ 6.0 的操作差异(一)之对话框中添加OnInitDialog()函数
查看>>
VC的MFC里面控件的ID使用ID_XXXXX和IDR_XXXXX的区别
查看>>
VC++ 获取ListControl选中行
查看>>
用VC++实现应用程序窗口的任意分割(2)
查看>>
“class”类型重定义,include(头文件)重复加载 QT /c++
查看>>
MFC框架类、文档类、视图类相互访问的方法
查看>>
<转>文档视图指针互获
查看>>
C++中头文件相互包含的几点问题
查看>>
内存设备描述表
查看>>
Latex插入eps图片的方法
查看>>
Matlab subplot 图像间距调整
查看>>
Hibernate使用count(*)取得表中记录总数
查看>>
distinct使SQL查询除去重复的字段
查看>>
从mysql中 导出/导入表及数据
查看>>
HQL语句大全(转)
查看>>
几个常用的Javascript字符串处理函数 spilt(),join(),substring()和indexof()
查看>>
javascript传参字符串 与引号的嵌套调用
查看>>
进程的状态
查看>>