JMX 的一个简单例子
废话不多说,上代码:
HelloWorldMBean接口
package com.acxiom.bilyao;public interface HelloWorldMBean {public void setGreeting(String greeting);public String getGreeting();public void sayHello();}
package com.acxiom.bilyao;import javax.management.Notification;import javax.management.NotificationBroadcasterSupport;public class HelloWorld extends NotificationBroadcasterSupport implements HelloWorldMBean {private String greeting = null;public HelloWorld() {this.greeting = "Hello World! I am a Standard MBean";}public HelloWorld(String greeting) {this.greeting = greeting;}@Overridepublic void setGreeting(String greeting) {this.greeting = greeting;Notification notification = new Notification("com.acxiom.bilyao.helloWorld.test", this, -1,System.currentTimeMillis(), greeting);sendNotification(notification);}@Overridepublic String getGreeting() {return greeting;}@Overridepublic void sayHello() {System.out.println(greeting);}}
package com.acxiom.bilyao;import java.lang.management.ManagementFactory;import javax.management.MBeanServer;import javax.management.Notification;import javax.management.NotificationListener;import javax.management.ObjectName;import com.sun.jdmk.comm.HtmlAdaptorServer;public class HelloAgent implements NotificationListener{private MBeanServer mbs = null;public HelloAgent() {mbs = ManagementFactory.getPlatformMBeanServer();//mbs = MBeanServerFactory.createMBeanServer("HelloAgent");HtmlAdaptorServer adapter = new HtmlAdaptorServer();HelloWorld hw = new HelloWorld();ObjectName helloName = null;ObjectName adapterName = null;try {helloName = new ObjectName("HelloAgent:name=helloworld");adapterName = new ObjectName("HelloAgent:name=htmladapter,port=8000");adapter.setPort(8000);mbs.registerMBean(adapter, adapterName);adapter.start();mbs.registerMBean(hw,helloName);hw.addNotificationListener( this, null, null );} catch(Exception e) {e.printStackTrace();}}private static void waitForEnterPressed() {try {System.out.println("Press <Enter> to continue...");System.in.read();} catch (Exception e) {e.printStackTrace();}}public static void main(String[] args) {HelloAgent ha = new HelloAgent();System.out.println("Hello Agent is running...");HelloAgent.waitForEnterPressed();}@Overridepublic void handleNotification(Notification notif, Object handback) {System.out.println( "Receiving notification..." );System.out.println( notif.getType() );System.out.println( notif.getMessage());}}