Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacement for SocketUtils.findAvailableTcpPort()?

The following initializes as socket with spring-integration on a dedicated port.

Goal is to give the application 2 minutes of time to run on that port, or fail is not successful. But the application start should not fail directly of that port is not free on startup!

@Configuration
@EnableIntegration
public class SocketConfiguration {    
        @Value("${app.port}")
        private String port;
    
        @Bean
        public TcpConnectionFactoryFactoryBean tcpFactory() {
            CompletableFuture.runAsync(() -> SocketUtils.findAvailableTcpPort(port, port)).get(2, TimeUnit.MINUTES);
        }
}

Problem: SocketUtils is @Deprecated since Spring Framework 6. What is a proper replacement for it?

The docs only state as an alternative:

Instead of using SocketUtils to find an available local port for a server, it is recommended that you rely on a server's ability to start on a random port

Well, that's not what I want, neither can I use if, because I'm historically bound to that specific port!

like image 733
membersound Avatar asked May 20 '26 21:05

membersound


1 Answers

There is a org.springframework.test.util.TestSocketUtils instead. But as Gary said it is better to rely on operation system choice via 0 for port option. Although why would one select a random port in a production code...

To get a real selected port you can listen for a TcpConnectionServerListeningEvent which will bring for you that actual value.

like image 189
Artem Bilan Avatar answered May 22 '26 09:05

Artem Bilan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!