0

我正在尝试编写另一个像RetriableProcessorDecorator下面这样的装饰器(作为一个单独的类),以便它在重试时产生指数延迟。例如,如果一条消息处理失败,我们等待 1 秒(应该是可配置的),然后是 2 秒,然后是 4 秒,然后是 8 秒,然后是 16 秒,等等。我想使用线程而不是忙等待,因为它更便宜. 我写了一个新的类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(我正在实现的新类):

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);
  }
}
4

1 回答 1

2

总的来说,我认为您的方法很好。

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

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);
于 2019-02-05T22:02:52.283 回答