如何实现指数延迟/睡眠以进行尝试和捕获

时间:2019-02-05 21:33:58

标签: java try-catch retry-logic

我正在尝试编写下面的mode = retry(get_variable) print(mode) 之类的另一个装饰器(作为一个单独的类),以便 重试会产生指数延迟。例如,如果消息无法处理,我们等待1秒钟(应可配置),然后等待2s,然后等待4s,然后等待8s,然后等待16s,依此类推。我想使用线程而不是忙等待,因为它比较便宜。我写了一个新的RetriableProcessorDecorator类,但是我不确定这是否是正确的方法。

RetriableProcessorDecorator.java:

RetriableProcessorExponentialDecorator

RetriableProcessorExponentialDecorator.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);
}
}

1 个答案:

答案 0 :(得分:1)

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

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

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