Notification
JMX API定义了一种机制,使MBean能生成通知,如当信号状态改变,检测到事件或者一个问题时。
要生成通知,MBean必须实现NotificationEmitter接口或继承NotificationBroadcasterSupport类。要发送一个通知必须构造Notification类的实例或者子类(如NotificationChangedAttribute),通知实例产生后,由NotificationBroadcasterSupport的sendNotification方法发送通知。
例:
Step 1 :定义HelloMBean接口
package com.jmx.demo5; public interface HelloMBean { public void sayHello(); public int add(int x, int y); public String getName(); public int getCacheSize(); public void setCacheSize(int size); }
package com.jmx.demo5; import javax.management.AttributeChangeNotification; import javax.management.MBeanNotificationInfo; import javax.management.Notification; import javax.management.NotificationBroadcasterSupport; //MBean must extends NotificationBroadcasterSupport or implements NotificationEmitter public class Hello extends NotificationBroadcasterSupport implements HelloMBean { private final String name = "Reginald"; private int cacheSize = DEFAULT_CACHE_SIZE; private static final int DEFAULT_CACHE_SIZE = 200; private long sequenceNumber = 1; public void sayHello() { System.out.println("hello, world"); } public int add(int x, int y) { return x + y; } public String getName() { return this.name; } public int getCacheSize() { return this.cacheSize; } public synchronized void setCacheSize(int size) { int oldSize = this.cacheSize; this.cacheSize = size; System.out.println("Cache size now " + this.cacheSize); /** * To send a notification,you need to construct an instance of class * Notification or a Subclass(such as AttributeChangedNotification),and * pass the instance to NotificationBroadcastSupport.sendNotification. * */ Notification n = new AttributeChangeNotification(this, sequenceNumber++, System.currentTimeMillis(), "CacheSize changed", "CacheSize", "int", oldSize, this.cacheSize); sendNotification(n); } @Override public MBeanNotificationInfo[] getNotificationInfo() { String[] types = new String[] { AttributeChangeNotification.ATTRIBUTE_CHANGE }; String name = AttributeChangeNotification.class.getName(); String description = "An attribute of this MBean has changed"; MBeanNotificationInfo info = new MBeanNotificationInfo(types, name, description); return new MBeanNotificationInfo[] { info }; } }
package com.jmx.demo5; import java.lang.management.ManagementFactory; import javax.management.MBeanServer; import javax.management.ObjectName; public class Main { public static void main(String[] args) throws Exception{ MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); ObjectName name = new ObjectName("com.jmx.demo:type=Hello"); Hello mbean = new Hello(); mbs.registerMBean(mbean, name); System.out.println("Waiting forever..."); Thread.sleep(Long.MAX_VALUE); } }
更改CacheSize的值后,在观察通知选项,变为1
总结:MBean实现通知机制,必须继承NotificationBroadcasterSupport类或实现NotificationEmitter接口,用Notification类构造通知实例,发送通知实例由NotificationBroadcaterSupport.sendNotification方法;