java项目中获取本项目端口号
2020-08-04 本文已影响0人
楼兰King
将此类作为bean组件交给spring管理
在需要使用的地方注入:
@Autowired
PortConfig portConfig;
import java.util.Iterator;
import java.util.Set;
import javax.management.MBeanServer;
import javax.management.MBeanServerFactory;
import javax.management.ObjectName;
import javax.management.Query;
import org.springframework.boot.web.context.WebServerInitializedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
/**
* 获取当前项目运行端口号---整合
*
*/
@Component
public class PortConfig implements ApplicationListener<WebServerInitializedEvent> {
private Integer port = 0;
/**
* 对外获取当前项目端口
* @return
*/
public Integer getProPort() {
if (this.port == 0) { // 表明当前项目运行在第三方插件(如tomcat)
this.port = getPort();
}
return this.port;
}
@Override
public void onApplicationEvent(WebServerInitializedEvent event) {
this.port = event.getWebServer().getPort();
}
/**
* 第三方获取项目端口
* @return
*/
private int getPort() {
try {
MBeanServer server;
if (MBeanServerFactory.findMBeanServer(null).size() > 0) {
server = MBeanServerFactory.findMBeanServer(null).get(0);
} else {
return -1;
}
Set<ObjectName> names = server.queryNames(new ObjectName("Catalina:type=Connector,*"),
Query.match(Query.attr("protocol"), Query.value("HTTP/1.1")));
Iterator<ObjectName> iterator = names.iterator();
if (iterator.hasNext()) {
ObjectName name = iterator.next();
return Integer.parseInt(server.getAttribute(name, "port").toString());
}
} catch (Exception e) {
e.printStackTrace();
}
return -1;
}
}