如何在集群中获得处理本次请求的web容器的端口号?
系统四台机器,每台机器部署四个Tomcat Web容器。现需要根据端口号随机切换到映射的数据源,若一台机器一个Tomcat则用IP识别,可现在一台机器四个Tomcat,因此还需要获得Web容器的端口号。
那么:在Web服务器集群中,一个Spring任务该如何获取Web容器的端口号呢?
设置需要的Key,本系统使用Tomcat Web服务器,操作如下。
编辑文件${tomact-dir}/bin/catalina.bat,添加以下内容即可:
set JAVA_OPTS=-D<key>="<value>",如:set JAVA_OPTS=-Dreyo.localPort="3400"
然后在程序System.getProperty("reyo.localPort")即可获取处理该次请求的Tomcat端口号。
1 import java.net.InetAddress; 2 import java.net.UnknownHostException; 3 4 public class SystemProperties { 5 6 public static InetAddress getInetAddress() { 7 try { 8 return InetAddress.getLocalHost(); 9 } catch (UnknownHostException e) { 10 System.out.println("unknown host!"); 11 } 12 return null; 13 } 14 15 public static String getHostIp(InetAddress netAddress) { 16 if (null == netAddress) { 17 return null; 18 } 19 String ip = netAddress.getHostAddress(); // get the ip address 20 return ip; 21 } 22 23 public static String getHostName(InetAddress netAddress) { 24 if (null == netAddress) { 25 return null; 26 } 27 String name = netAddress.getHostName(); // get the host address 28 return name; 29 } 30 31 public static String getPort(){ 32 return System.getProperty("reyo.localPort"); 33 } 34 35 public static void main(String[] args) { 36 InetAddress netAddress = getInetAddress(); 37 System.out.println("host ip:" + getHostIp(netAddress)); 38 System.out.println("host name:" + getHostName(netAddress)); 39 System.out.println("port:" + getPort()); 40 try { 41 InetAddress netAddressa = InetAddress.getLocalHost(); 42 String hostAddress = netAddressa.getHostAddress(); 43 System.out.println(hostAddress); 44 } catch (UnknownHostException e) { 45 logger.error("位置主机!!!", e); 46 } 47 } 48 49 }
参考资料:
集群: 如何在spring 任务中 获得集群中的一个web 容器的端口号?
Done