java – 具有业务异常的Hystrix断路器

我观察到Hystrix将所有来自命令的异常视为断路故障.它包括从命令run()方法抛出并由Hystrix本身创建的异常,例如: HystrixTimeoutException.

但我有从run()方法抛出的业务异常,表示服务响应有效错误,必须进一步处理.
这种异常的一个例子是使用SpringWS的WebServiceTemplate时的WebServiceFaultException.

所以我不需要那些特定的例外来使电路跳闸.
如何实现这种行为?

有一种明显的方法可以将业务异常包装到holder对象中,从run()方法返回它,然后将它展开回Exception并重新抛出.但它想知道是否有更清洁的方式.

最佳答案 有以下解决方案.

返回异常而不是抛出

最直接和最脏的方法.这看起来有点时髦,因为你必须将命令擦除到Object并且有很多类型转换.

Observable<BusinessResponse> observable = new HystrixCommand<Object>() {
    @Override
    protected Object run() throws Exception {
        try {
            return doStuff(...);
        } catch (BusinessException e) {
            return e; // so Hystrix won't treat it as a failure
        }
    }
})
.observe()
.flatMap(new Func1<Object, Observable<BusinessResponse>>() {
    @Override
    public Observable<BusinessResponse> call(Object o) {
        if (o instanceof BusinessException) {
            return Observable.error((BusinessException)o);
        } else {
            return Observable.just((BusinessResponse)o);
        }
    }
});

使用holder对象来保存结果和异常

这个apporach需要引入额外的持有者类(也可以用于其他目的).

class ResultHolder<T, E extends Exception> {
    private T result;
    private E exception;

    public ResultHolder(T result) {
        this.result = result;
    }
    public ResultHolder(E exception) {
        if (exception == null) {
            throw new IllegalArgumentException("exception can not be null");
        }
        this.exception = exception;
    }

    public T get() throws E {
        if (exception != null) {
            throw exception;
        } else {
            return result;
        }
    }

    public Observable<T> observe() {
        if (exception != null) {
            return Observable.error(exception);
        } else {
            return Observable.just(result);
        }
    }

    @SuppressWarnings("unchecked")
    public static <T, E extends Exception> ResultHolder<T, E> wrap(BusinessMethod<T, E> method) {
        try {
            return new ResultHolder<>(method.call());
        } catch (Exception e) {
            return new ResultHolder<>((E)e);
        }
    }


    public static <T, E extends Exception> Observable<T> unwrap(ResultHolder<T, E> holder) {
        return holder.observe();
    }

    interface BusinessMethod<T, E extends Exception> {
        T call() throws E;
    }
}

现在使用它的代码看起来更干净,唯一的缺点可能是相当多的泛型.此方法在Java 8中也是最好的,其中lambdas和方法引用可用,否则它看起来很笨重.

new HystrixCommand<ResultHolder<BusinessResponse, BusinessException>>() {
    @Override
    protected ResultHolder<BusinessResponse, BusinessException> run() throws Exception {
        return ResultHolder.wrap(() -> doStuff(...));
    }
}
.observe()
.flatMap(ResultHolder::unwrap);

使用HystrixBadRequestException

HystrixBadRequestException是一种特殊的异常,在断路器和指标方面不会算作失败.如documentation所示:

Unlike all other exceptions thrown by a HystrixCommand this will not
trigger fallback, not count against failure metrics and thus not
trigger the circuit breaker.

HystrixBadRequestException的实例不是由Hystrix本身创建的,因此将其用作业务异常的包装是安全的.但是,原始业务异常仍需要解包.

new HystrixCommand<BusinessResponse>() {
    @Override
    protected BusinessResponse run() throws Exception {
        try {
            return doStuff(...);
        } catch (BusinessException e) {
            throw new HystrixBadRequestException("Business exception occurred", e);
        }
    }
}
.observe()
.onErrorResumeNext(e -> {
    if (e instanceof HystrixBadRequestException) {
        e = e.getCause(); // Unwrap original BusinessException
    }
    return Observable.error(e);
})
点赞