来斌 2011-03-11
这里说下tomcat对DynamicMBean的实现和封装。利用tomcat包,可以轻松实现将自己的对象注册为MBeans。
看个例子就明白了。
package com.MBean.test; import org.apache.tomcat.util.modeler.BaseNotificationBroadcaster; public class DyMBeanObj extends BaseNotificationBroadcaster{ public int getConnectionNumber() { return this .conNum ; } public synchronized void setConnectionNumber( int con_Num ) { this .conNum = con_Num ; System.out.println("Connection Number now " + this .conNum ); } private int conNum = DEFAULT_CON_Num; private static final int DEFAULT_CON_Num= 20 ; }
package com.MBean.test; import org.apache.tomcat.util.modeler.BaseNotificationBroadcaster; public class DyMBeanObj extends BaseNotificationBroadcaster{ public int getConnectionNumber() { return this.conNum ; } public synchronized void setConnectionNumber(int con_Num ) { this.conNum = con_Num ; System.out.println("Connection Number now " + this.conNum ); } private int conNum = DEFAULT_CON_Num; private static final int DEFAULT_CON_Num= 20; }
package com.MBean.test; import javax.management.*; import org.apache.tomcat.util.modeler.Registry; public class DyMBeanTest { /** * @param args */ public static void main(String[] args) throws Exception{ // TODO Auto-generated method stub DyMBeanObj obj = new DyMBeanObj(); //将这个Object-->动态MBean ObjectName on = null ; on = new ObjectName( "com.MBeans:type=test" ); //此MBean的域和类型 Registry.getRegistry(null , null ).registerComponent(obj, on, null ); System.out.println("Waiting for incoming requests..." ); Thread.sleep(Long.MAX_VALUE); } }
package com.MBean.test; import javax.management.*; import org.apache.tomcat.util.modeler.Registry; public class DyMBeanTest { /** * @param args */ public static void main(String[] args) throws Exception{ // TODO Auto-generated method stub DyMBeanObj obj = new DyMBeanObj();//将这个Object-->动态MBean ObjectName on = null; on = new ObjectName("com.MBeans:type=test");//此MBean的域和类型 Registry.getRegistry(null, null).registerComponent(obj, on, null); System.out.println("Waiting for incoming requests..."); Thread.sleep(Long.MAX_VALUE); } }
查看运行效果,可以直接看上篇文章。
不管是DynamicMBean还是StandardMBean,都需要ObjectName,可以利用一串字符构造这个对象。
”com.MBeans:type=test“,其实就是Domain:key=value
Registry大大简化了DynamicMBean的调用,讲MBeanServer的create也封装了。