通过注解使用Hystrix

参考: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<User> getUserByIdAsync(final String id) {
        return new AsyncResult<User>() {
            @Override
            public User invoke() {
                return userResource.getUserById(id);
            }
        };
    }
3、响应执行--------这块我也不太了解,平常也用不到,貌似使用的rx包下Obervable类,在Android开发中用的比较平凡
@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(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());
        }


  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值