我正在尝试连接到一个远程websocket端点(在spring引导应用程序中),如果它抛出一个异常,我将使用弹性4j- retry v1.7.7和JDK 8重试连接。然而,弹性4j-重试尝试连接一次,如果失败,不要重试。我做错了什么,连接是在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";
}
}发布于 2021-12-13 10:59:37
以下代码起作用了,
@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进行初始化,问题中的代码也将工作。我喜欢上面的代码更干净。
https://stackoverflow.com/questions/70331601
复制相似问题