JMX使用報java.lang.ClassNotFoundException: org.apache.naming.java.javaURLContextFactory

    項目需求:經過JMX監控ZooKeeper,效果相似jconsole,但以web方式展示。在使用過程當中,web容器中的JMX鏈接MBeanServer獲取鏈接時,老是失敗,提示信息:java.lang.ClassNotFoundException: org.apache.naming.java.javaURLContextFactory。但經過main方法調用的時候,是能夠正常訪問的。java

    代碼以下:web

String jmxURL = "service:jmx:rmi:///jndi/rmi://" + ip + ":" + jmxport + "/jmxrmi";
			// jmxurl
			JMXServiceURL serviceURL = new JMXServiceURL(jmxURL);

			Map<String, String[]> map = new HashMap<String, String[]>();
			String[] credentials = new String[] { userName, password };
			map.put("jmx.remote.credentials", credentials);
			connector = JMXConnectorFactory.connect(serviceURL, map);
			MBeanServerConnection mbsc = connector.getMBeanServerConnection();

後從網上搜索資料,從一篇文章(http://canofy.iteye.com/blog/758748)中獲到瞭解決方法,修改了MBeanServerConnection的獲取方式,而後就能夠正常運行了,修改後的代碼以下:apache

Registry registry = LocateRegistry.getRegistry(host, Integer.parseInt(port));
			RMIServer stub = null;
			if (stub == null) {
				stub = (RMIServer) registry.lookup("jmxrmi");
			}
			Map<String, String[]> map = new HashMap<String, String[]>();
			String[] credentials = new String[] { username, password };
			map.put("jmx.remote.credentials", credentials);
			connector = new RMIConnector(stub, null);
			connector.connect(map);
			mbsc = connector.getMBeanServerConnection();

 

MBeanServerConnection有兩種獲取方式,通常狀況下,兩種獲取方式均可以,某些特殊應用,API上面意思是最好使用第二種方法。url

相關文章
相關標籤/搜索