使用MBean获取tomcat和jboss端口

/**
	 * 根据协议和scheme获取服务端口号
	 * 
	 * @param protocol
	 * @param scheme
	 * @return
	 */
	protected Integer getPortByMBean(String protocol, String scheme) {
		MBeanServer mBeanServer = null;
		ArrayList<MBeanServer> mBeanServers = MBeanServerFactory.findMBeanServer(null);
		
		int serverType = 1;
		if(mBeanServers.size() > 0) {
			for (MBeanServer _mBeanServer : mBeanServers) {
				if(_mBeanServer instanceof JmxMBeanServer) {
					mBeanServer = _mBeanServer;
					break;
				} else if("jboss".equals(_mBeanServer.getDefaultDomain())) {
					mBeanServer = _mBeanServer;
					serverType = 2;
				} else {
					throw new IllegalStateException("无法识别JVM中关联的MBeanServer.");
				}
			}
		}
		if(mBeanServer == null) {
			throw new IllegalStateException("没有发现JVM中关联的MBeanServer.");
		}
		
		Set<ObjectName> objectNames = null;
		
		try {
			if(serverType == 1) {
				objectNames = mBeanServer.queryNames(new ObjectName("Catalina:type=Connector,*"), null);
			}
			else if(serverType == 2) {
				objectNames = mBeanServer.queryNames(new ObjectName("jboss.web:type=Connector,*"), null);
			}
		} catch (MalformedObjectNameException e) {
			e.printStackTrace();
		} catch (NullPointerException e) {
			e.printStackTrace();
		}
		
		if(objectNames == null || objectNames.size() <= 0) {
			throw new IllegalStateException("没有发现JVM中关联的MBeanServer : " + mBeanServer.getDefaultDomain() + " 中的对象名称.");
		}
		
		try {
			for (ObjectName objectName : objectNames) {
				Object _protocol = mBeanServer.getAttribute(objectName, "protocol");
				Object _scheme = mBeanServer.getAttribute(objectName, "scheme");
				
				if(protocol.equals(_protocol) && scheme.equals(_scheme)) {
					return (Integer) mBeanServer.getAttribute(objectName, "port");
				}
			}
		} catch (AttributeNotFoundException e) {
			e.printStackTrace();
		} catch (InstanceNotFoundException e) {
			e.printStackTrace();
		} catch (MBeanException e) {
			e.printStackTrace();
		} catch (ReflectionException e) {
			e.printStackTrace();
		}
		
		return null;
	}

你可能感兴趣的:(tomcat,jboss,Mbean)