系统四台机器,每台机器部署四个Tomcat Web容器。现需要根据端口号随机切换到映射的数据源,若一台机器一个Tomcat则用IP识别,可现在一台机器四个Tomcat,因此还需要获得Web容器的端口号。
那么:在Web服务器集群中,一个Spring任务该如何获取Web容器的端口号呢?
设置需要的Key,本系统使用Tomcat Web服务器,操作如下。
编辑文件${tomact-dir}/bin/catalina.bat,添加以下内容即可:
然后在程序System.getProperty("reyo.localPort")即可获取处理该次请求的Tomcat端口号。
import java.net.InetAddress;
import java.net.UnknownHostException; public class SystemProperties { public static InetAddress getInetAddress() {
try {
return InetAddress.getLocalHost();
} catch (UnknownHostException e) {
System.out.println("unknown host!");
}
return null;
} public static String getHostIp(InetAddress netAddress) {
if (null == netAddress) {
return null;
}
String ip = netAddress.getHostAddress(); // get the ip address
return ip;
} public static String getHostName(InetAddress netAddress) {
if (null == netAddress) {
return null;
}
String name = netAddress.getHostName(); // get the host address
return name;
} public static String getPort(){
return System.getProperty("reyo.localPort");
} public static void main(String[] args) {
InetAddress netAddress = getInetAddress();
System.out.println("host ip:" + getHostIp(netAddress));
System.out.println("host name:" + getHostName(netAddress));
System.out.println("port:" + getPort());
try {
InetAddress netAddressa = InetAddress.getLocalHost();
String hostAddress = netAddressa.getHostAddress();
System.out.println(hostAddress);
} catch (UnknownHostException e) {
logger.error("位置主机!!!", e);
}
} }
参考资料:
集群: 如何在spring 任务中 获得集群中的一个web 容器的端口号?
Done