重试HystrixCommand

时间:2017-02-17 11:35:10

标签: rx-java reactive-programming hystrix

我注意到重试失败的HystrixCommand只是重放发出的错误。在某些情况下,我想重播它。一个实例是下游服务限制请求的情况;我想等一下再试一次。

我可以看到的一种方法是使用Observable.defer,但我确信这是一种更好的方式。

final AtomicInteger tries = new AtomicInteger(0);
final AtomicInteger retries = new AtomicInteger(0);

final Observable<Integer> command = Observable.defer(() -> new HystrixCommand<Integer>(HystrixCommandGroupKey.Factory.asKey("test")) {
            @Override
            protected Integer run() throws Exception {
                final int i = tries.incrementAndGet();
                System.out.print("Try: " + i);
                if (i < 5) {
                    throw new ProvisionedThroughputExceededException("exceeded");
                }
                return i;
            }
        }.observe()
)
        .retry((attempts, error) -> {
            final Class<? extends Throwable> rootClass = Throwables.getRootCause(error).getClass();
            if (ProvisionedThroughputExceededException.class.isAssignableFrom(rootClass)) {
                final int i = retries.incrementAndGet();
                return i < 5;
            }
            return false;
        });

final int attempts = command.toBlocking().single();
assertEquals(5, attempts);
assertEquals(4, retries.get());

0 个答案:

没有答案