Setting a Random Port in Spring Boot Application at startup

Carvia Tech | December 17, 2017 | 2 min read | 273 views


Why Random Port?

In Microservices architecture, its often required to start multiple instances of the same service on same host. To achieve this we need to set a dynamically available port in certain range [say 5000-6000] at the application startup.

Spring 4.0 has introduced a simple utility class to facilitate the port lookup.

SocketUtils

SocketUtils is Simple utility methods for working with network sockets — for example, for finding available ports on {@code localhost}.

Within this class, a TCP port refers to a port for a {@link ServerSocket}; whereas, a UDP port refers to a port for a {@link DatagramSocket}.

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.SocketUtils;
import org.springframework.util.StringUtils;

public class SpringBootUtil {
    final static Logger log = LoggerFactory.getLogger(SpringBootUtil.class);

    public static void setRandomPort(int minPort, int maxPort) {
        try {
            String userDefinedPort = System.getProperty("server.port", System.getenv("SERVER_PORT"));
            if(StringUtils.isEmpty(userDefinedPort)) {
                int port = SocketUtils.findAvailableTcpPort(minPort, maxPort);    (1)
                System.setProperty("server.port", String.valueOf(port));
                log.info("Server port set to {}.", port);
            }
        } catch( IllegalStateException e) {
            log.warn("No port available in range 5000-5100. Default embedded server configuration will be used.");
        }
    }

    public static void setRandomPort() {
        setRandomPort(5000, 5100);
    }
}
1 SocketUtils.findAvailableTcpPort method finds an available TCP port randomly selected from the range

Using this utility in Spring Boot Application is quite easy, we just need to call SpringBootUtil. setRandomPort(5000, 6000) as the first line in main method.

Spring Boot Main Class
public static void main(String[] args) {
        SpringBootUtil.setRandomPort();    (1)
        ApplicationContext ctx = SpringApplication.run(Application.class, args);
        logger.info("Application " + ctx.getApplicationName() + " started");
}
Notes
1 We set the random port in first line of main method.

Now we have enabled out spring microservice to start on a random available port in predefined range. This port will be registered in Eureka Service Discovery so that other peer services can access this micro service.


Top articles in this category:
  1. Run method on application startup in Spring Boot
  2. Custom banner in spring boot application
  3. Running Spring Boot app as a service in unix
  4. Spring Boot 2.0 Reactive Web Performance Metrics
  5. How will you test web layer in Spring Boot using WebMvcTest annotation?
  6. Prevent Lost Updates in Database Transaction using Spring Hibernate
  7. What is new in Spring Boot 2



Find more on this topic:
Spring Framework image
Spring Framework

Spring Framework - MVC, Dependency Injection, Spring Hibernate, Spring Data JPA, Spring Boot and Spring Cloud for Microservices Architecture.

Last updated 1 week ago


Recommended books for interview preparation:

This website uses cookies to ensure you get the best experience on our website. more info