Skip to content

Commit 2ac5243

Browse files
xujinxujin
authored andcommitted
fix本地启动管理端口占用开随机端口
1 parent 5b356da commit 2ac5243

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

moss-client/moss-client-1.x/src/main/java/org/xujin/moss/client/config/ManagementEnvironmentCustomizer.java

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,12 +8,19 @@
88
import org.springframework.core.io.support.PropertiesLoaderUtils;
99

1010
import java.io.IOException;
11+
import java.net.InetAddress;
12+
import java.net.Socket;
1113
import java.util.Properties;
1214

1315
/**
1416
* 内嵌 Web 容器模式运行时,指定一些 Management 的属性配置
1517
*/
1618
public class ManagementEnvironmentCustomizer implements EnvironmentCustomizer<ConfigurableEnvironment> {
19+
20+
private static final String SPRINGBOOT_MANAGEMENT_PORT_KEY = "management.port";
21+
22+
private static final int SPRINGBOOT_MANAGEMENT_PORT_VALUE = 8081;
23+
1724
private static final Log logger = LogFactory.getLog(AdminEndpointApplicationRunListener.class);
1825
private static final String DEFAULT_PROPERTY = "META-INF/moss-client/bootstrap.properties";
1926
@Override
@@ -22,9 +29,25 @@ public void customize(ConfigurableEnvironment env) {
2229
Properties props;
2330
ClassPathResource resource = new ClassPathResource(DEFAULT_PROPERTY);
2431
props = PropertiesLoaderUtils.loadProperties(resource);
32+
props.put(SPRINGBOOT_MANAGEMENT_PORT_KEY, getManagementPort(env));
2533
env.getPropertySources().addLast(new PropertiesPropertySource("managementProperties", props));
2634
} catch (IOException e) {
2735
logger.error("Failed to load " + DEFAULT_PROPERTY);
2836
}
2937
}
38+
39+
private int getManagementPort(ConfigurableEnvironment env) {
40+
if (!"prod".equalsIgnoreCase(env.getProperty("spring.profiles.active"))) {
41+
try {
42+
//不是生产环境,使用Socket去连接如果能连接上表示端口被占用
43+
InetAddress Address = InetAddress.getByName("127.0.0.1");
44+
Socket socket = new Socket(Address, SPRINGBOOT_MANAGEMENT_PORT_VALUE);
45+
logger.info(SPRINGBOOT_MANAGEMENT_PORT_VALUE+":port is used,return:0");
46+
return 0;
47+
} catch (IOException e) {
48+
logger.info(SPRINGBOOT_MANAGEMENT_PORT_VALUE+":port is not used");
49+
}
50+
}
51+
return SPRINGBOOT_MANAGEMENT_PORT_VALUE;
52+
}
3053
}

0 commit comments

Comments
 (0)