JMX入門案例,使用Jconsole鏈接

今天給大家分享一個JMX入門的案例,JMX是Java平臺上爲應用程序、設備、系統等植入管理功能的框架。JMX可以跨越一系列異構操作系統平臺、系統體系結構和網絡傳輸協議,靈活的開發無縫集成的系統、網絡和服務管理應用。直接上代碼。

HelloMBean.java

package com.xz.helloworld.jmx;

public interface HelloMBean {

	public String getName();
	
	public void setName(String name);
	
	void printString(String str);
	
}

Hello.java

package com.xz.helloworld.jmx;

public class Hello implements HelloMBean{

	private String name;
	
	@Override
	public String getName() {
		// TODO Auto-generated method stub
		System.out.println("set name : " + name);
		return name;
	}

	@Override
	public void setName(String name) {
		System.out.println("set name : " + name);
		this.name = name;
	}

	@Override
	public void printString(String str) {
		System.out.println("printString  "+str);
	}

}

TestMain.java

package com.xz.helloworld.jmx;

import java.rmi.registry.LocateRegistry;

import javax.management.MBeanServer;
import javax.management.MBeanServerFactory;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import javax.management.remote.JMXConnectorServer;
import javax.management.remote.JMXConnectorServerFactory;
import javax.management.remote.JMXServiceURL;

public class TestMain {

	public static void main(String[] args) throws Exception {

		MBeanServer server = MBeanServerFactory.createMBeanServer();
		ObjectName helloName = new ObjectName("xxxx:name=HelloWorld");
		server.registerMBean(new Hello(), helloName);

		LocateRegistry.createRegistry(8088);
		JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://127.0.0.1:8088/jmxrmi");
		JMXConnectorServer jsc = JMXConnectorServerFactory.newJMXConnectorServer(url, null, server);
		jsc.start();

		Thread.sleep(100000);

	}

}

這個時候我們啓動項目,通過jconsole去鏈接,如圖:

這裏用來模擬遠程的進程鏈接,不使用本地的進程,如果服務部署服務器上的時候就必須通過遠程來鏈接了。

接下來我們給Name屬性設置一個值:

寫好之後點擊這裏的刷新,我們可以在控制檯看到:

 可以看到已經成功調用到方法了。下面我們來看看Java客戶端。

public static void clientInit() {
		
		try {
			String url = "service:jmx:rmi:///jndi/rmi://127.0.0.1:8088/jmxrmi";
			JMXServiceURL serviceUrl = new JMXServiceURL(url);
			JMXConnector connector = JMXConnectorFactory.connect(serviceUrl);
			MBeanServerConnection connection = connector.getMBeanServerConnection();
			Set<ObjectName> objectNames = connection.queryNames(null, null);
			for(ObjectName objectName:objectNames) {
				System.out.println("========" + objectName + "========");
				  MBeanInfo mBeanInfo = connection.getMBeanInfo(objectName);
				  System.out.println("[Attributes]");
				  for (MBeanAttributeInfo attr : mBeanInfo.getAttributes()) {
				    Object value = null;
				    try {
				      value = attr.isReadable() ? connection.getAttribute(objectName, attr.getName()) : "";
				    } catch (Exception e) {
				      value = e.getMessage();
				    }
				    System.out.println(attr.getName() + ":" + value);
				  }
				  System.out.println("[Operations]");
				  for (MBeanOperationInfo oper : mBeanInfo.getOperations()) {
					  System.out.println(oper.getName() + ":" + oper.getDescription());
				  }
				  System.out.println("[Notifications]");
				  for (MBeanNotificationInfo notice : mBeanInfo.getNotifications()) {
					  System.out.println(notice.getName() + ":" + notice.getDescription());
				  }
			}
			
			
			ObjectName objectName = new ObjectName("xxxx:name=HelloWorld");
//			connection.addNotificationListener(objectName, new NotificationListener() {
//				
//				@Override
//				public void handleNotification(Notification notification, Object handback) {
//					System.out.println("\nReceived notification:");
//				    System.out.println("\tClassName: " + notification.getClass().getName());
//				    System.out.println("\tSource: " + notification.getSource());
//				    System.out.println("\tType: " + notification.getType());
//				    System.out.println("\tMessage: " + notification.getMessage());
//				    if (notification instanceof AttributeChangeNotification) {
//				      AttributeChangeNotification acn =
//				        (AttributeChangeNotification) notification;
//				      System.out.println("\tAttributeName: " + acn.getAttributeName());
//				      System.out.println("\tAttributeType: " + acn.getAttributeType());
//				      System.out.println("\tNewValue: " + acn.getNewValue());
//				      System.out.println("\tOldValue: " + acn.getOldValue());
//				    }
//				}
//			}, null, null);
			
			//給MBean賦值
			connection.setAttribute(objectName, new Attribute("Name", "我是張三"));
			//獲取MBean的值
			Object Name = connection.getAttribute(objectName, "Name");
			System.out.println(Name);
			
			//調用MBean的方法
			connection.invoke(objectName, "printString", new Object[] {"我是Object"}, new String[] {String.class.getCanonicalName()});
			
			System.out.println("---"+String.class.getCanonicalName());
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	

在上面的main方法中通過 開啓一個線程去調用,即可看到效果。

========JMImplementation:type=MBeanServerDelegate========
[Attributes]
MBeanServerId:DESKTOP-LPKSION_1576138303413
SpecificationName:Java Management Extensions
SpecificationVersion:1.4
SpecificationVendor:Oracle Corporation
ImplementationName:JMX
ImplementationVersion:1.8.0_221-b11
ImplementationVendor:Oracle Corporation
[Operations]
[Notifications]
javax.management.MBeanServerNotification:Notifications sent by the MBeanServerDelegate MBean
========xxxx:name=HelloWorld========
[Attributes]
set name : null
Name:null
[Operations]
printString:Operation exposed for management
[Notifications]
set name : 我是張三
set name : 我是張三
我是張三
printString  我是Object
---java.lang.String

當然JMX裏邊還有很多比較強大的東西,也有很多玩法,這篇文章就介紹到此,有建議的朋友可以在評論區留言,技術問題可以私信我。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章