8
8
import org .springframework .core .io .support .PropertiesLoaderUtils ;
9
9
10
10
import java .io .IOException ;
11
+ import java .net .InetAddress ;
12
+ import java .net .Socket ;
11
13
import java .util .Properties ;
12
14
13
15
/**
14
16
* 内嵌 Web 容器模式运行时,指定一些 Management 的属性配置
15
17
*/
16
18
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
+
17
24
private static final Log logger = LogFactory .getLog (AdminEndpointApplicationRunListener .class );
18
25
private static final String DEFAULT_PROPERTY = "META-INF/moss-client/bootstrap.properties" ;
19
26
@ Override
@@ -22,9 +29,25 @@ public void customize(ConfigurableEnvironment env) {
22
29
Properties props ;
23
30
ClassPathResource resource = new ClassPathResource (DEFAULT_PROPERTY );
24
31
props = PropertiesLoaderUtils .loadProperties (resource );
32
+ props .put (SPRINGBOOT_MANAGEMENT_PORT_KEY , getManagementPort (env ));
25
33
env .getPropertySources ().addLast (new PropertiesPropertySource ("managementProperties" , props ));
26
34
} catch (IOException e ) {
27
35
logger .error ("Failed to load " + DEFAULT_PROPERTY );
28
36
}
29
37
}
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
+ }
30
53
}
0 commit comments