【Java】JMX Notification

一、发送通知

熟系观察者模式、活着写过Android或用过消息队列的应该都比较熟悉一个场景,就是当数据变化时,变化方通知所有的订阅方。
JMX里就提供了这样的消息订阅、通知机制。

二、示例

创建OperationMBean接口:

public interface OperationMBean {
    void setVal(int v);
    int getVal();
}

创建Operation实现OperationMBean接口:

public class Operation extends NotificationBroadcasterSupport implements OperationMBean {

    private final AtomicLong sequenceNumber = new AtomicLong( 1 );

    private int val;

    @Override
    public int getVal() {
        return val;
    }

    @Override
    public void setVal(int v) {
        int oldVal = this.val;
        this.val = v;
        /**
        1.通知源的对象名称,即HelloMBean,简单表示为this
		2.一个序列号,在此示例中为长名称sequenceNumber,设置为1并递增
		3.时间戳记
		4.通知消息的内容
		5.在这种情况下,已更改的属性的名称 cacheSize
		6.更改的属性类型
		7.在这种情况下,旧的属性值 oldSize
		8.在这种情况下,新的属性值 this.cacheSize
        */
        AttributeChangeNotification notification = new AttributeChangeNotification(
                this,
                sequenceNumber.getAndIncrement(),
                System.currentTimeMillis(),
                AttributeChangeNotification.ATTRIBUTE_CHANGE,
                "Change!Change!Change!Change!Change!",
                "int",
                oldVal,
                this.val );
        sendNotification( notification );
    }
}

托管MBean:

public class NotifyServer {
    public static void main(String[] args) throws Exception {
        MBeanServer server = ManagementFactory.getPlatformMBeanServer();
        Operation config = new Operation();
        server.registerMBean( config, new ObjectName( "com.haya.com:type=notifications.Operation" ) );
        Thread.sleep(Long.MAX_VALUE);
    }
}

接下来启动Jconsole、找到operation会发现多了一个通知选项
在这里插入图片描述
选中通知会发现什么都没有,不过先不着急,点击一下订阅:
在这里插入图片描述
然后切换到属性,修改val
在这里插入图片描述
你就会发现通知+1了
在这里插入图片描述


版权声明:本文为HuaLingPiaoXue原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。