0

我正在尝试连接到远程 websocket 端点(在 spring boot 应用程序内),如果它引发异常,我将使用带有 JDK 8 的弹性 4j-retry v1.7.7 重试连接。但是,resilience4j-retry 尝试连接一次,如果失败,请不要重试。我做错了什么,连接被调用ApplicationReadyEvent

    @Autowired
    private WsConnector connector;

    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
        RetryConfig config = RetryConfig.custom()
                .maxAttempts(5)
                .waitDuration(Duration.ofSeconds(5))
                .build();

        RetryRegistry registry = RetryRegistry.of(config);
        Retry retry = registry.retry("retryableSupplier", config);

        CheckedFunction0<String> retryableSupplier = Retry.decorateCheckedSupplier(retry, connector::startConnection);
        try {
            System.out.println("retrying " + retryableSupplier.apply());
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }

        Retry.EventPublisher publisher = retry.getEventPublisher();
        publisher.onRetry(event1 -> System.out.println(event1.toString()));
        publisher.onSuccess(event2 -> System.out.println(event2.toString()));
    }
    @Service
    public class WsConnector {
        public String startConnection() throws Exception {
            WebSocketContainer container = ContainerProvider.getWebSocketContainer();
            WSClient client = new WSClient();
            container.connectToServer(client, new URI("ws://viewpoint:8080/ping"));
            return "Connected";
        }
    }
4

1 回答 1

0

以下代码有效,

     @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
        RetryConfig config = RetryConfig.custom()
                .maxAttempts(5)
                .waitDuration(Duration.ofSeconds(5))
                .build();

        RetryRegistry registry = RetryRegistry.of(config);
        Retry retry = registry.retry("retryableSupplier", config);
        CheckedFunction0<String> checkedSupplier = Retry.decorateCheckedSupplier(retry, connector::startConnection);

        Retry.EventPublisher publisher = retry.getEventPublisher();
        publisher.onRetry(event1 -> System.out.println("Retrying: " + event1.toString()));
        publisher.onSuccess(event2 -> System.out.println("Retrying Success: " +event2.toString()));

        Try<String> result = Try.of(checkedSupplier).recover((throwable -> "I am recovered"));
        System.out.println("result: " + result);
    }

问题出在事件上,它正在工作,但是在我重试后EventPublisher初始化时不可见。EventPublisher因此,问题中的代码也可以EventPublisher在重试开始之前进行初始化。我喜欢上面的代码更干净。

于 2021-12-13T10:59:37.790 回答