前言:做了一个监控应用服务器的项目(支持Tocmat、WebSphere、WebLogic各版本), 过程也算是磕磕绊绊,由于网上缺少相关资料,或者深陷于知识的海洋难以寻觅到有效的资料,因而走过不少弯路,遇过不少困难。为了留下点印记,给后来人留下 点经验之谈,助之少走弯路,故将这些经验整理出来,与大家分享。水平有限,难免疏漏,还望指正。如有疑问,欢迎留言,或者加入Q群参与讨 论:35526521。

在写WebLogic监控程序的过程中,可以说是相当坎坷,因为需要支持WebLogic不同版本,而WebLogic不同版本对JMX的支持却有着不小的差别,在网上也没有找到完整的解决方案,所以只能自己一点点的摸索,不过拨云见日了。在此,我们只探讨监控WebLogic 8.x的解决方案,其他版本后续跟进,我会整理出一个完整的文章。为什么监控WebLogic 8.x要先单独写个文章呢——因为8.x跟新的9.x和10.x不一样,刚开始入手会遇到很头疼的问题。

好了,不啰嗦了,我们开始:

 

只能在JDK1.4下监控WebLogic Server 8.x

首先,上面所说的那个最头疼的问题就是——要访问WebLogic Server 8.x的MBeans,必须是在JDK1.4环境下 ,如果是JDK5+环境下会很麻烦, 原因如下 :

----------------------------------------------------------------------------------------------------------------------

因为1.4的时代JDK还没有提供javax.management包,所 以WebLogic 8.x的weblogic.jar中自己包含了javax.management包,而JDK5中也有javax.management包,JVM运行时 会优先加载JDK5中javax.management包里的类,而weblogic.jar和JDK5中javax.management的实现是不一 样的,因此会产生错误。而且weblogic8.x支持JMX 1.0,而JDK5支持JMX1.2 。

----------------------------------------------------------------------------------------------------------------------

网上有人说通过System.setProperty("jmx.serial.form", "1.0");这样的设置可以解决问题,经试验根本不行。

 

监控WebLogic Server 8.x需要的JAR包

  1、 weblogic.jar

  2、 webservices.jar

可以在%WL_HOME%\server\lib目录下找到这两个JAR包。

如果只加入weblogic.jar 包,有些 API 可以访问,但是运行MBeanHome -> getAllMBeans() 方法获取所有MBean时会抛异常:

weblogic.rjvm.PeerGoneException: ; nested exception is: weblogic.utils.NestedException: Ljavax/xml/soap/SOAPException; - with nested exception: [java.lang.NoClassDefFoundError: Ljavax/xml/soap/SOAPException;] at weblogic.rjvm.BasicOutboundRequest.sendReceive(BasicOutboundRequest.java:108) at weblogic.rmi.internal.BasicRemoteRef.invoke(BasicRemoteRef.java:164) at weblogic.management.internal.AdminMBeanHomeImpl_815_WLStub.getAllMBeans(Unknown Source) at cn.chenfeng.jmx.weblogic.ListAllMBeans.main(ListAllMBeans.java:27) Caused by: weblogic.utils.NestedException: Ljavax/xml/soap/SOAPException; - with nested exception: [java.lang.NoClassDefFoundError: Ljavax/xml/soap/SOAPException;] at weblogic.rjvm.RJVMImpl.gotExceptionReceiving(RJVMImpl.java:967) at weblogic.rjvm.ConnectionManager.gotExceptionReceiving(ConnectionManager.java:930) at weblogic.rjvm.t3.T3JVMConnection.hasException(T3JVMConnection.java:870) at weblogic.socket.SocketMuxer.deliverExceptionAndCleanup(SocketMuxer.java:588) at weblogic.socket.SocketMuxer.deliverHasException(SocketMuxer.java:544) at weblogic.socket.JavaSocketMuxer.processSockets(JavaSocketMuxer.java:306) at weblogic.socket.SocketReaderRequest.execute(SocketReaderRequest.java:32) at weblogic.kernel.ExecuteThread.execute(ExecuteThread.java:224) at weblogic.kernel.ExecuteThread.run(ExecuteThread.java:183) --------------- nested within: ------------------ weblogic.rmi.extensions.RemoteRuntimeException: Unexpected Exception - with nested exception: [weblogic.rjvm.PeerGoneException: ; nested exception is: weblogic.utils.NestedException: Ljavax/xml/soap/SOAPException; - with nested exception: [java.lang.NoClassDefFoundError: Ljavax/xml/soap/SOAPException;]] at weblogic.management.internal.AdminMBeanHomeImpl_815_WLStub.getAllMBeans(Unknown Source) at cn.chenfeng.jmx.weblogic.ListAllMBeans.main(ListAllMBeans.java:27)

 

解决办法:
加入webservices.jar包就可以解决这个问题了。

 

在JDK5+环境下监控WebLogic Server 8.x

如果要在JDK5+环境下监控WebLogic Server 8.x,必须写自定义classloader,屏蔽JDK自己的javax.management包,转而优先加载weblogic.jar中的 javax.management包。这可谓一大难题,但是只要对JVM的类加载机制非常熟悉就可以解决。

 

但是即使这样,还存在一个问题,通过weblogic.management.Helper得到Admin MBeanHome或Local MBeanHome的代码(已经使用自定义ClassLoader并改造成反射的方式从而使自定义ClassLoader生效),以Java Application的方式运行没有问题,但是作为Web应用部署到Tomcat以后会报异常:
----------------------------------------------------------------------------------------------------------------------

JNDI naming exception: javax.naming.NameNotFoundException: Name weblogic.management.adminhome is not bound in this Context

----------------------------------------------------------------------------------------------------------------------

具体原因不明,后来查到官方资料有这样的说法,见官方说明:


 

也就是说要通过MBeanServer接口的方式访问MBean,示例代码如下,此代码只能在JDK1.4环境下运行,要到JDK5+下运行必须使用自定义的ClassLoader,当然这些代码也要改造成用反射的方式(或者有一个“入口”是通过反射调用的,以保证处于同一ClassLoader下),这样自定义的ClassLoader才能生效:

 

String url = "t3://192.168.1.2:7001";
String username = "weblogic";
String password = "weblogic";

Hashtable props = new Hashtable();
props.put(Context.PROVIDER_URL, url);
props.put(Context.INITIAL_CONTEXT_FACTORY,"weblogic.jndi.WLInitialContextFactory");
props.put(Context.SECURITY_PRINCIPAL, username);
props.put(Context.SECURITY_CREDENTIALS, password);
InitialContext ctx = new InitialContext(props);

MBeanServer mbeanServer = (MBeanServer) ctx.lookup("weblogic.management.server");

 

 

下面展示一个较完整的Demo

package cn.chenfeng.jmx.weblogic;

import java.util.Hashtable;
import java.util.Iterator;
import java.util.Set;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import javax.naming.Context;
import javax.naming.InitialContext;
import weblogic.jndi.Environment;
import weblogic.management.Helper;
import weblogic.management.MBeanHome;
import weblogic.management.configuration.DomainMBean;
import weblogic.management.configuration.ServerMBean;
import weblogic.management.runtime.RuntimeMBean;

/**
 * 使用MBeanHome的getMBeansByType和getRuntimeMBean方法获取MBean
 * @author 陈峰
 */
public class WebLogicMonitor {
	public static void main(String[] args) {
		WebLogicMonitor monitor = new WebLogicMonitor();
		try {
			monitor.collectData8();
		} catch (Exception e) {
			e.printStackTrace();
		}
		System.out.println();
		try {
			monitor.collectData8_3();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void collectData8() throws Exception {

		final String providerUrl = "t3://192.168.1.2:7001";
		final String username = "weblogic";
		final String password = "weblogic";

		MBeanHome home = (MBeanHome) Helper.getAdminMBeanHome(username,
				password, providerUrl);
		System.out.println("Admin MBeanHome --> DomainName : "
				+ home.getDomainName());

		/*
		 * 获取MBeanHome的另一个方法,Helper内部就是通过这种方法实现的
		 */
		{
			Environment env = new Environment();
			env.setProviderUrl(providerUrl);
			env.setSecurityPrincipal(username);
			env.setSecurityCredentials(password);
			Context ctx = env.getInitialContext();

			MBeanHome localHome = (MBeanHome) ctx
					.lookup(MBeanHome.LOCAL_JNDI_NAME);
			MBeanHome adminHome = (MBeanHome) ctx
					.lookup(MBeanHome.ADMIN_JNDI_NAME);
			System.out.println("Local MBeanHome --> DomainName : "
					+ localHome.getDomainName());
			System.out.println("Admin MBeanHome --> DomainName : "
					+ adminHome.getDomainName());
		}

		{
			Set mbeans = home.getMBeansByType("ServerRuntime");
			System.out.println("ServerRuntime MBeans : " + mbeans);
		}

		{
			System.out
					.println("\n===============获取DomainMBean再获取其他信息==================");
			DomainMBean domainMBean = home.getActiveDomain();
			System.out.println("DomainMBean --> Name : "
					+ domainMBean.getName());
			System.out.println("DomainMBean --> ObjectName : "
					+ domainMBean.getObjectName());

			int adminPort = domainMBean.getAdministrationPort();
			System.out.println("DomainMBean --> Administration Port : "
					+ adminPort);

			String consoleContextPath = domainMBean.getConsoleContextPath();
			System.out.println("DomainMBean --> Console Context Path : "
					+ consoleContextPath);

			ServerMBean[] servers = domainMBean.getServers();
			for (int i = 0; i < servers.length; i++) {
				ServerMBean server = servers[i];
				System.out
						.println("DomainMBean --> ServerMBean --> ObjectName : "
								+ server.getObjectName());
			}
		}

		/**
		 * JDBC连接池,根据Type获取指定类型的MBeans
		 */
		{
			System.out
					.println("\n===============获取JDBC连接池信息==================");
			Set mbeans = home.getMBeansByType("JDBCConnectionPoolRuntime");
			System.out.println("JDBCConnectionPoolRuntime MBeans : " + mbeans);

			Iterator itt = mbeans.iterator();
			while (itt.hasNext()) {
				RuntimeMBean mbean = (RuntimeMBean) itt.next();
				String name = mbean.getName();
				int count = Integer.parseInt(mbean.getAttribute(
						"ActiveConnectionsCurrentCount").toString());
				System.out.println("【JDBCConnectionPoolRuntime --> " + name
						+ " --> ActiveConnectionsCurrentCount】: " + count);
			}
		}

		/**
		 * 根据Name和Type获取指定RuntimeMBean
		 */
		{
			System.out
					.println("\n===============根据Name和Type获取指定RuntimeMBean==================");
			RuntimeMBean mbean = home.getRuntimeMBean("MedRecXAPool-PointBase",
					"JDBCConnectionPoolRuntime");
			System.out.println(mbean.getObjectName());
		}

	}

	public void collectData8_3() throws Exception {
		System.out.println("=============== 获取MBeanServer ================");

		String url = "t3://192.168.1.2:7001"; // URL of the server instance
		String username = "weblogic";
		String password = "weblogic";

		Hashtable props = new Hashtable();
		props.put(Context.PROVIDER_URL, url);
		props.put(Context.INITIAL_CONTEXT_FACTORY,
				"weblogic.jndi.WLInitialContextFactory");
		props.put(Context.SECURITY_PRINCIPAL, username);
		props.put(Context.SECURITY_CREDENTIALS, password);
		InitialContext ctx = new InitialContext(props);

		MBeanServer mbeanServer = (MBeanServer) ctx
				.lookup("weblogic.management.server");

		System.out.println("MBeanServer:" + mbeanServer);

		Set jdbcMBeans = mbeanServer.queryNames(new ObjectName(
				"*:Type=JDBCConnectionPool,*"), null);
		for (Iterator itt = jdbcMBeans.iterator(); itt.hasNext();) {
			Object jdbcMBean = itt.next();
			System.out.println(jdbcMBean);
		}
	}
}