JMX API 定义了一种机制,使得MBean可以产生notification,以在状态变化时、特定事件发生时或者出问题时,发出一个提醒。
state change, a detected event, a problem
generate notification : MBean必须implement NotificationEmitter或extend NotificationBroadcasterSupport。
send notification : 创建javax.management.Notification或者其子类,并调用NotificationBroadcasterSupport.sendNotification()
source:
每个notification都会有个源(source),就是相应的ObjectName。
sequence number:
每个notification都会有个sequence number。用于给来自同一个source的notification编号。
当处理notification的顺序有影响的时候,sequence number就派上用场了。
可以是0,但最好不要是一个source每生成一个notification时,就增加一下。
示例:
package test.xue.mbean; import javax.management.AttributeChangeNotification; import javax.management.Notification; import javax.management.NotificationBroadcasterSupport; public class Hello extends NotificationBroadcasterSupport implements HelloMBean { private final String name = "My HelloMBean"; private int cacheSize = 1024; private String title; private long sequenceNo = 1; @Override public void sayHello() { System.out.println("hello, my HelloMBean"); } @Override public int add(int x, int y) { return x + y; } @Override public String getName() { return name; } @Override public int getCacheSize() { return cacheSize; } @Override public synchronized void setCacheSize(int size) { int oldSize = this.cacheSize; this.cacheSize = size; System.out.println("cacheSize changed : " + size); Notification notification = new AttributeChangeNotification(this, sequenceNo++, System.currentTimeMillis(), "cacheSize changed", "cacheSize", "int", oldSize, this.cacheSize); sendNotification(notification); } @Override public void setText() { System.out.println("setText called"); } @Override public void settitle(String title) { this.title = title; System.out.println("title changed : " + title); } }
JConsole测试:
点击“订阅”,以后才能接收到source发出的notification。
修改了属性CacheSize后,JConsole会接到通知。