Java 通量。有没有办法在最后一个元素上重试?

Java 通量。有没有办法在最后一个元素上重试?,java,flux,reactive,Java,Flux,Reactive,Flux是否允许在不将指针移到初始位置的情况下对发生的异常重试操作?我的意思是从“有问题的”元素 例如: Flux.fromArray(new Integer[]{1, 2, 3}) .delayElements(Duration.ofSeconds(1)) .doOnNext(i -> { System.out.println("i: " + i); if (i == 2) {

Flux是否允许在不将指针移到初始位置的情况下对发生的异常重试操作?我的意思是从“有问题的”元素

例如:

Flux.fromArray(new Integer[]{1, 2, 3})
        .delayElements(Duration.ofSeconds(1))
        .doOnNext(i -> {
            System.out.println("i: " + i);
            if (i == 2) {
                System.out.println("2 found");
                throw new RuntimeException("2!!!!!!!1");
            }
        })
        .retry(2)
        .subscribe();
将具有以下输出:

i: 1
i: 2
2 found
i: 1
i: 2
2 found
i: 1
i: 2
2 found
当我希望看到这样的输出时:

i: 1
i: 2
2 found
i: 2
2 found
i: 2
2 found

顺便说一句,skipUntil不是我想要的,据我所知不是,但我可能错了

但是,您可以自己为该特定步骤提供该逻辑。例如,创建您自己的使用者并在其中包装重试逻辑

public class RetryConsumer<T> implements Consumer<T> {

    private int                 retryCount;
    private Consumer<? super T> delegate;

    public RetryConsumer(int retryCount, Consumer<? super T> delegate) {
        this.retryCount = retryCount;
        this.delegate = delegate;
    }

    @Override
    public void accept(T value) {

        int currentAttempts = 0;
        while (currentAttempts < retryCount) {
            try {
                delegate.accept(value);
                break;
            } catch (Throwable e) {
                currentAttempts++;
                if (currentAttempts == retryCount) {
                    throw e;
                }
                //Still have some attempts left
            }
        }

    }
}
公共类RetryConsumer实现消费者{
私人内部检索计数;

私人消费者我不知道,但我可能错了

但是,您可以自己为特定步骤提供该逻辑

public class RetryConsumer<T> implements Consumer<T> {

    private int                 retryCount;
    private Consumer<? super T> delegate;

    public RetryConsumer(int retryCount, Consumer<? super T> delegate) {
        this.retryCount = retryCount;
        this.delegate = delegate;
    }

    @Override
    public void accept(T value) {

        int currentAttempts = 0;
        while (currentAttempts < retryCount) {
            try {
                delegate.accept(value);
                break;
            } catch (Throwable e) {
                currentAttempts++;
                if (currentAttempts == retryCount) {
                    throw e;
                }
                //Still have some attempts left
            }
        }

    }
}
公共类RetryConsumer实现消费者{
私人内部检索计数;

private ConsumerInteresting,但通常遵循
skipUntil
的方法,当我用不可变的无状态对象替换整数时会出现问题,我只尝试处理一次,并尝试使用
重试
以避免一些可能的失败。有趣的是,通常遵循
skipUntil
的方法,这有问题当我用不可变的无状态对象替换整数时,我尝试只处理一次,并用
retry
重试一些可能的失败。