检测新注册的MBean

Mar*_*rcB 6 java jmx mbeans

我在Java 1.6中使用平台MBeans服务器,在OSGi容器中运行.

主要使用MBean作为统计计数器和事件.它们的实现在一个包中,但它们在其他几个包中实例化.每个MBean都使用平台MBean服务器自行注册.

问题是当我通过JMX附加并查询MBean时,我只获得当前注册的那些,并且在它们被实例化之前它们不会被注册(因为静态类在第一次访问之前不存在,或者因为捆绑还没有开始,或者计数器深入一些逻辑,直到第一次使用才会存在)

我需要一些在MBean服务器中订阅"注册"事件的方法.或者确定何时向服务器添加新MBean的其他方法.检测已删除的MBean将是一个额外的好处,但不是必需的.

我得到的唯一解决方案基本上是一个每隔5秒轮询一次服务器的线程,并将结果与​​保存的MBean列表进行比较,这非常难看.

Nic*_*las 13

所有兼容的MBeanServers都将通知侦听器MBean注册和取消注册事件.关键是在MBeanServerDelegate上注册通知监听器.

例如,javax.management.NotificationListener实现:

public class MBeanEventListener implements NotificationListener {
    public void handleNotification(Notification notification, Object handback) {
        MBeanServerNotification mbs = (MBeanServerNotification) notification;
        if(MBeanServerNotification.REGISTRATION_NOTIFICATION.equals(mbs.getType())) {
            log("MBean Registered [" + mbs.getMBeanName() + "]");
        } else if(MBeanServerNotification.UNREGISTRATION_NOTIFICATION.equals(mbs.getType())) {
            log("MBean Unregistered [" + mbs.getMBeanName() + "]");
        }
    }       
}
Run Code Online (Sandbox Code Playgroud)

要注册侦听器,请针对MBeanServerDelegate添加通知侦听器.如果要筛选实际通知的MBean,可以使用MBeanServerNotificationFilter.在此示例中,为所有ObjectName启用了过滤器.

    // Get a reference to the target MBeanServer
    MBeanServerConnection server = ManagementFactory.getPlatformMBeanServer();
    MBeanServerNotificationFilter filter = new MBeanServerNotificationFilter();
    filter.enableAllObjectNames();
    server.addNotificationListener(MBeanServerDelegate.DELEGATE_NAME, new MBeanEventListener(), filter, null);
Run Code Online (Sandbox Code Playgroud)

每次注册或取消注册MBean时,您的侦听器实现都将获得回调.