From 59f07d37abbef2675472e6ff265133163da9c8f3 Mon Sep 17 00:00:00 2001 From: Dave Syer Date: Fri, 22 Nov 2013 19:59:06 +0000 Subject: [PATCH] Scan for port near default --- .../autoconfigure/web/ServerProperties.java | 22 ++++++++++++++++++- .../web/ServerPropertiesTests.java | 9 ++++++++ 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/ServerProperties.java b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/ServerProperties.java index 76caeadaf9c..9132b4df5aa 100644 --- a/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/ServerProperties.java +++ b/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/ServerProperties.java @@ -113,7 +113,7 @@ public class ServerProperties implements EmbeddedServletContainerCustomizer { public void customize(ConfigurableEmbeddedServletContainerFactory factory) { Integer port = getPort(); if (this.scan) { - port = SocketUtils.findAvailableTcpPort(port != null ? 8080 : port); + port = scanForPort(port); } if (port != null) { factory.setPort(port); @@ -132,6 +132,26 @@ public class ServerProperties implements EmbeddedServletContainerCustomizer { } } + private Integer scanForPort(Integer port) { + boolean found = false; + int delta = 1; + port = port == null ? 8080 : port; + while (!found) { + try { + port = SocketUtils.findAvailableTcpPort(port, port + delta); + found = true; + } + catch (IllegalStateException e) { + if (delta > 65536) { + throw e; + } + delta = delta > 5 ? delta > 100 ? delta * 4 : delta * 3 : delta * 2; + } + port = port + delta; + } + return port; + } + public static class Tomcat { private String accessLogPattern; diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/ServerPropertiesTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/ServerPropertiesTests.java index be56375ed67..cc3df622210 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/ServerPropertiesTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/ServerPropertiesTests.java @@ -80,6 +80,15 @@ public class ServerPropertiesTests { assertTrue(factory.getPort() > 1000); } + @Test + public void testPortScanFromHigher() throws Exception { + this.properties.setScan(true); + this.properties.setPort(5678); + ConfigurableEmbeddedServletContainerFactory factory = new MockEmbeddedServletContainerFactory(); + this.properties.customize(factory); + assertTrue(factory.getPort() < 6000); + } + // FIXME test customize }