首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >重试threadsafe是否返回修饰函数?

重试threadsafe是否返回修饰函数?
EN

Stack Overflow用户
提问于 2019-05-17 23:15:45
回答 1查看 361关注 0票数 2

我有一个向远程服务发送消息的类,如下所示。我正在使用resilience4j-retry重试网络调用。根据文档,因为重试实例是线程安全的,所以我在类级别创建它并重用它。

代码语言:javascript
运行
复制
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函数时重复它。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-05-24 11:42:17

在查看resilience4j-retry代码后,我发现修饰后的函数实际上是线程安全的;只要我们首先修饰的函数是线程安全的。

由于postMessage函数是线程安全的,因此修饰后的postMessageFunction函数也是线程安全的,所以我可以像下面这样重写代码。

代码语言:javascript
运行
复制
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;
    }

}    
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56189295

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档