我正在尝试编写另一个像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);
}
}