listeneruserclient.java

来自「jmx codeJava源码」· Java 代码 · 共 93 行

JAVA
93
字号

package book.jmx.examples;

import javax.management.*;
import java.util.List;

public class ListenerUserClient {

   public void run() {

      try {
         // Find an agent from this JVM. Null argument will return
         // a list of all MBeanServer instances.
         List srvrList = MBeanServerFactory.findMBeanServer(null);
         MBeanServer server = 
               (MBeanServer)srvrList.iterator().next();
         
         // register the MBean to the server
         NotificationListener listener = new UserListener(server);
         NotificationFilter filter     = new NotificationFilter() {
                  
            public boolean isNotificationEnabled(Notification notification) {
               return 
                     (notification.getType().equals("example.user.remove"))
                     ? true
                     : false;
            }
         };

         ObjectName john = new ObjectName("example:name=John");
         server.registerMBean(new BroadcastingUser(), john);
         server.setAttribute(john, new Attribute("Name", "John"));
         server.addNotificationListener(john, listener, filter, john);
         
         ObjectName mike = new ObjectName("example:name=Mike");
         server.registerMBean(new BroadcastingUser(), mike);
         server.setAttribute(mike, new Attribute("Name", "Mike"));
         server.addNotificationListener(mike, listener, filter, mike);
         
         ObjectName xena = new ObjectName("example:name=Xena");
         server.registerMBean(new BroadcastingUser(), xena);
         server.setAttribute(xena, new Attribute("Name", "Xena"));
         server.addNotificationListener(xena, listener, filter, xena);
         
         server.invoke(john, "remove", null, null);
         server.invoke(mike, "remove", null, null);
         server.invoke(xena, "remove", null, null);
         
      }
      catch (JMException e) {
         e.printStackTrace();
      }
   }


   //
   class UserListener implements NotificationListener {
      
      MBeanServer server = null;
      
      UserListener(MBeanServer server) {
         this.server = server;
      }
      
      public void handleNotification(Notification notification,
                                     Object handback) {
                                        
         try {
            System.out.println(notification.getMessage());
            server.unregisterMBean((ObjectName)handback);
         }
         catch (JMException e) {
            e.printStackTrace();
         }
      }      
   }
   

   //
   // Main method for the client. This will instantiate
   // an agent in the JVM.
   //
   public static void main(String[] args) {
    
         MBeanServer server =
               MBeanServerFactory.createMBeanServer();
     
         new ListenerUserClient().run();
   }   
}


⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?