在專案啟動時(無request)獲取Tomcat埠號
阿新 • • 發佈:2019-01-21
上一篇說的將非Spring Boot專案註冊到Eureka Server並提供服務也說到,配置檔案裡eureka.port必須要與本機tomcat埠號相同,但不同環境往往有不同的tomcat埠號,以往我使用不同環境的配置檔案以確保eureka服務埠與tomcat一致。
1.讀tomcat配置檔案
這是最先想到的方法,通過classpath一層層找到conf下的server.xml拿埠號,因為路徑基本不會變,所以也是一種方法,由於發現了更好的方法,此處並無程式碼…
2.通過Jmx 的MBeanServer
package com.kowalski.demo;
import javax.management .MBeanServer;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import javax.management.Query;
import java.lang.management.ManagementFactory;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Set;
public class IPAddressKowalski{
public static String getIpAddressAndPort() throws MalformedObjectNameException, NullPointerException,
UnknownHostException {
MBeanServer beanServer = ManagementFactory.getPlatformMBeanServer ();
Set<ObjectName> objectNames = beanServer.queryNames(new ObjectName("*:type=Connector,*"),
Query.match(Query.attr("protocol"), Query.value("HTTP/1.1")));
String host = InetAddress.getLocalHost().getHostAddress();
String port = objectNames.iterator().next ().getKeyProperty("port");
String ipadd = "http" + "://" + host + ":" + port;
System.out.println(ipadd);
return ipadd;
}
public static int getTomcatPort() throws MalformedObjectNameException, NullPointerException {
MBeanServer beanServer = ManagementFactory.getPlatformMBeanServer();
Set<ObjectName> objectNames = beanServer.queryNames(new ObjectName("*:type=Connector,*"),
Query.match(Query.attr("protocol"), Query.value("HTTP/1.1")));
String port = objectNames.iterator().next().getKeyProperty("port");
return Integer.valueOf(port);
}
}
那麼之前寫的將非Boot專案註冊到eureka server上怎麼動態的拿tomcat埠號呢:
在之前的MyInstanceConfig 中加入方法:
/***
*獲取本機啟動中tomcat埠號
* @return
*/
@Override
public int getNonSecurePort(){
int tomcatPort;
try {
MBeanServer beanServer = ManagementFactory.getPlatformMBeanServer();
Set<ObjectName> objectNames = beanServer.queryNames(new ObjectName("*:type=Connector,*"),
Query.match(Query.attr("protocol"), Query.value("HTTP/1.1")));
tomcatPort = Integer.valueOf(objectNames.iterator().next().getKeyProperty("port"));
}catch (Exception e){
return super.getNonSecurePort();
}
return tomcatPort;
}
這裡的getNonSecurePort其實就是config.properties裡面配置的eureka.port可以在PropertiesInstanceConfig的init方法中找到