我有一个向远程服务发送消息的类,如下所示。我正在使用resilience4j-retry重试网络调用。根据文档,因为重试实例是线程安全的,所以我在类级别创建它并重用它。
public class RemoteMessageService {
Retry retry = Retry.of("RemoteMessageService", RetryConfig.custom()
.maxAttempts(5)
.retryExceptions(ProcessingException.class)
.intervalFunction(IntervalFunction.ofExponentialBackoff())
.build());
public void postMessageWithRetry(final String message){
Function<Integer, Void> postMessageFunction = Retry.decorateFunction(retry, this::postMessage);
try {
postMessageFunction.apply(message)
} catch (final ProcessingException e) {
LOG.warn("Got processing exception: {}", e.getMessage());
} catch (final Exception e) {
LOG.error("Got unknown exception: {}", e.getMessage());
}
}
private Void postMessage(final String message){
// Do a network call to send the message to a rest service
// throw ProcessingException in case of timeout
return null;
}
}
我的问题是,Retry.decorateFunction(retry, this::postMessage);
返回的修饰函数是否也是线程安全的?
在这种情况下,我可以将它移到类级别,而不是在每次调用postMessageWithRetry函数时重复它。
发布于 2019-05-24 11:42:17
在查看resilience4j-retry
代码后,我发现修饰后的函数实际上是线程安全的;只要我们首先修饰的函数是线程安全的。
由于postMessage
函数是线程安全的,因此修饰后的postMessageFunction
函数也是线程安全的,所以我可以像下面这样重写代码。
public class RemoteMessageService {
private final Retry retry = Retry.of("RemoteMessageService", RetryConfig.custom()
.maxAttempts(5)
.retryExceptions(ProcessingException.class)
.intervalFunction(IntervalFunction.ofExponentialBackoff())
.build());
private final Function<Integer, Void> postMessageFunction = Retry.decorateFunction(retry, this::postMessage);
public void postMessageWithRetry(final String message) {
try {
postMessageFunction.apply(message)
} catch (final ProcessingException e) {
LOG.warn("Got processing exception: {}", e.getMessage());
} catch (final Exception e) {
LOG.error("Got unknown exception: {}", e.getMessage());
}
}
private Void postMessage(final String message) {
// Do a network call to send the message to a rest service
// throw ProcessingException in case of timeout
return null;
}
}
https://stackoverflow.com/questions/56189295
复制相似问题