SpringBoot获取项目ip和端口号【内置和外置获取的两种方式】

当Springboot以内置的tomcat启动的时候,直接采用Spring提供的ApplicationListener接口来监听项目的启动,在启动的时候获取到项目的端口号即可。当Springboot,打成War包,放到外部tomcat中部署的时候,就需要剔除内置的tomcat容器,此时Springboot的启动流程就和上面不一样,好像就不再有初始化WebServer的步骤了。

@Configuration
public class ServerConfig  implements ApplicationListener<WebServerInitializedEvent> { 
    
    private int serverPort;

	//获取内置tomcat端口号
    @Override
    public void onApplicationEvent(WebServerInitializedEvent event) { 
        this.serverPort = event.getWebServer().getPort();
    }
    
    // 获取项目IP
    public String getIp() { 
        InetAddress address = null;
        try { 
            address = InetAddress.getLocalHost();
        } catch (UnknownHostException e) { 
            e.printStackTrace();
        }
        if(this.serverPort == 0){ // 获取外置tomcat端口号
			this.serverPort = getTomcatPort();
		}
        return "http://"+address.getHostAddress() +":"+this.serverPort;
    }
    
    public int getTomcatPort() {
        MBeanServer beanServer = ManagementFactory.getPlatformMBeanServer();
        try {
            QueryExp protocol = Query.match(Query.attr("protocol"), Query.value("HTTP/1.1"));
            ObjectName name = new ObjectName("*:type=Connector,*");
            Set<ObjectName> objectNames = beanServer.queryNames(name, protocol);
            for (ObjectName objectName : objectNames) {
                String catalina = objectName.getDomain();
                if ("Catalina".equals(catalina)) {
                    return Integer.parseInt(objectName.getKeyProperty("port"));
                }
            }
        } catch (MalformedObjectNameException e) {
            e.printStackTrace();
        }
        return 0;
    }
}

使用

@Autowired
private ServerConfig serverConfig;

public String getIp() { 
   return  serverConfig.getIp();
}

你可能感兴趣的:(JAVA,spring,boot,tcp/ip,java)