Skip to content

Commit 5b356da

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

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed

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

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,11 @@
2222
*/
2323
public class ManagementEnvironmentCustomizer implements EnvironmentCustomizer<ConfigurableEnvironment> {
2424

25+
26+
private static final int SPRINGBOOT_MANAGEMENT_PORT_VALUE = 8081;
27+
28+
private static final String SPRINGBOOT_MANAGEMENT_PORT_KEY = "management.server.port";
29+
2530
private static final Log logger = LogFactory.getLog(AdminEndpointApplicationRunListener.class);
2631

2732
private static final String DEFAULT_PROPERTY = "META-INF/moss-client/bootstrap.properties";
@@ -32,9 +37,25 @@ public void customize(ConfigurableEnvironment env) {
3237
Properties props;
3338
ClassPathResource resource = new ClassPathResource(DEFAULT_PROPERTY);
3439
props = PropertiesLoaderUtils.loadProperties(resource);
40+
props.put(SPRINGBOOT_MANAGEMENT_PORT_KEY, getManagementPort(env));
3541
env.getPropertySources().addLast(new PropertiesPropertySource("managementProperties", props));
3642
} catch (IOException e) {
3743
logger.error("Failed to load " + DEFAULT_PROPERTY);
3844
}
3945
}
46+
47+
private int getManagementPort(ConfigurableEnvironment env) {
48+
if (!"prod".equalsIgnoreCase(env.getProperty("spring.profiles.active"))) {
49+
try {
50+
//不是生产环境,使用Socket去连接如果能连接上表示端口被占用
51+
InetAddress Address = InetAddress.getByName("127.0.0.1");
52+
Socket socket = new Socket(Address, SPRINGBOOT_MANAGEMENT_PORT_VALUE);
53+
logger.info(SPRINGBOOT_MANAGEMENT_PORT_VALUE+":port is used,return:0");
54+
return 0;
55+
} catch (IOException e) {
56+
logger.info(SPRINGBOOT_MANAGEMENT_PORT_VALUE+":port is not used");
57+
}
58+
}
59+
return SPRINGBOOT_MANAGEMENT_PORT_VALUE ;
60+
}
4061
}

0 commit comments

Comments
 (0)