Find randomly bound port of RSocket server in Spring

Taking advantage of randomly assigned ports in Spring Boot tests that exercise a RSocket server can be somewhat convoluted. It’s not obvious how to connect a RSocket client when the server is bound to any available port via the property-value of spring.rsocket.server.port=0.

Ultimately it boils down to registering an application event listener that is notified of RSocketServerInitializedEvent, from which the address and port of the RSocket server can be derived.

@TestConfiguration
public class TestRSocketClientConfig implements ApplicationListener<RSocketServerInitializedEvent> {

  private final AtomicInteger rsocketServerPort = new AtomicInteger(-1);

  @Override
  public void onApplicationEvent(RSocketServerInitializedEvent event) {
        rsocketServerPort.compareAndExchange(-1, event.getServer().address().getPort());
  }
}

The RSocket client bean should be initialized lazily so that the transport is configured after the port is identified after server startup.

@Lazy
@Bean
public RSocketRequester getTestRSocketRequester(RSocketRequester.Builder builder) {
    return builder
            .rsocketConnector(rSocketConnector -> rSocketConnector.reconnect(Retry.backoff(5, Duration.ofSeconds(3))))
            .dataMimeType(APPLICATION_CBOR)
            .transport(TcpClientTransport.create(rsocketServerPort.get()));
}
Previous
Previous

Stateful Property Testing a CRDT with jetCheck

Next
Next

In praise of Sony Digital Paper