我们的服务是部署在weblogic上的,最近遇到一个需求,需要在代码中获取weblogic部署当前服务的IP地址和端口。
后来搜到一段代码,亲测有效:
public static String getIpAndPort(){
try {
InitialContext initialContext = new InitialContext();
MBeanServer tMBeanServer;
MBeanServer platformMBeanServer = ManagementFactory.getPlatformMBeanServer();
tMBeanServer = (MBeanServer) initialContext.lookup("java:comp/env/jmx/runtime");
ObjectName tObjectName = new ObjectName(
"com.bea:Name=RuntimeService,Type=weblogic.management.mbeanservers.runtime.RuntimeServiceMBean");
ObjectName serverrt = (ObjectName) tMBeanServer.getAttribute(tObjectName, "ServerRuntime");
String port = String.valueOf(tMBeanServer.getAttribute(serverrt, "ListenPort"));
String listenAddr = (String) tMBeanServer.getAttribute(serverrt, "ListenAddress");
String[] tempAddr = listenAddr.split("/");
if (tempAddr.length == 1) {
listenAddr = tempAddr[0];
} else if (tempAddr[tempAddr.length - 1].trim().length() != 0) {
listenAddr = tempAddr[tempAddr.length - 1];
} else if (tempAddr.length > 2) {
listenAddr = tempAddr[tempAddr.length - 2];
}
StringBuilder sBuilder = new StringBuilder(listenAddr);
sBuilder.append(":");
sBuilder.append(port);
System.out.print(sBuilder);
return sBuilder.toString();
} catch (NamingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MalformedObjectNameException e) {
// TODO Auto-generated catch block
e.pri