如何为 try & catch 实现指数 delay/sleep

How to implement exponential delay/sleep for try & catch

我正在尝试编写另一个装饰器,例如下面的 RetriableProcessorDecorator(作为单独的 class),以便 它在重试时会出现指数延迟。例如,如果消息处理失败,我们等待 1 秒(应该是可配置的),然后是 2 秒,然后是 4 秒,然后是 8 秒,然后是 16 秒,等等。我想使用线程而不是忙等待,因为它更便宜.我写了一个新的 class RetriableProcessorExponentialDecorator 来执行此操作,但我不确定这是否是正确的方法。

RetriableProcessorDecorator.java:

@Slf4j
@Setter
@RequiredArgsConstructor
@AllArgsConstructor(access = AccessLevel.PACKAGE)
public class RetriableProcessorDecorator implements.   
AbsMessageProcessorDecorator {
private final AbsMessageProcessor messageProcessor;
@Autowired
private AbsMessageActiveMQConfiguration configuration;

@Override
public void onMessage(AbsMessage message) throws Exception {
    int executionCounter = 0;
    final int maxRetries = this.configuration.getExceptionRetry() + 1;
    do {
        executionCounter++;
        try {
            this.messageProcessor.onMessage(message);
        } catch (RetriableException e) {
            log.info("Failed to process message. Retry #{}", executionCounter);
        } catch (Exception e) {
            // We don't retry on this, only RetriableException.
            throw e;
        }
    } while (executionCounter < maxRetries);
}
}

RetriableProcessorExponentialDecorator.java(新的class我正在实施):

public class RetriableProcessorExponentialDecorator implements AbsMessageProcessorDecorator {
  private final AbsMessageProcessor messageProcessor;
  @Autowired
  private AbsMessageActiveMQConfiguration configuration;

  @Override
  public void onMessage(AbsMessage message) throws Exception {
    int executionCounter = 0;
    int delayCounter = 1000;
    final int maxRetries = this.configuration.getExceptionRetry() + 1;
    do {
      executionCounter++;
      try {
        this.messageProcessor.onMessage(message);
      } catch (RetriableException e) {
        log.info("Failed to process message. Retry #{}", executionCounter);
        Thread.sleep(delayCounter);
        delayCounter = delayCounter * 2;
      } catch (Exception e) {
        // We don't retry on this, only RetriableException.
        throw e;
      }
    } while (executionCounter < maxRetries && delayCounter < Long.MAX_VALUE);
  }
}

总的来说,我觉得你的做法很好。

但是,如果您想使其可配置(即更有用),那么您可以执行以下操作:

double multiplier = 2.0; // make this configurable
...
delayCounter = (long) (delayCounter * (Math.pow(multiplier, executionCounter)));
Thread.sleep(delayCounter);

您还可以添加一种配置最大延迟的方法,这对于某些用例可能很方便,例如:

long maxDelay = 300000; // 5 minutes
...
if (delayCounter > maxDelay) {
   delayCounter = maxDelay;
}
Thread.sleep(delayCounter);