读书人

简略的MBean的实现

发布时间: 2012-12-19 14:13:14 作者: rapoo

简单的MBean的实现

有两种Java MBean类型:静态MBean和动态MBean。

?

1.静态MBean

?

首先讨论静态MBean。要定义一个静态MBean,对于MBean接口类有一个约定:就是接口名必须以MBean为后缀,例如:HelloWorldMBean;然后对于这个接口的实现类名也有一个约定,就是接口名去掉MBean后缀,例如前面HelloWorldMBean对应的实现类名为HelloWorld。

?

在接口中,定义为以set或get方法开头的,被认为是一个属性值;其他方法被认为是一个操作。例如:

public interface HelloWorldMBean {public String getName();public void setName(String name);public String print();public int getAge();public void setSex(String sex);}
?

以上定义的MBean中,有三个属性:name, age和sex;有一个操作:print。剩下的就是在实现类的实现对应的方法,这样就定义完一个MBean类型。

?

下面就是注册这个MBean。

?

MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();HelloWorldMBean bean = new HelloWorld();ObjectName objectName = new ObjectName("com.talend.liugang.jmx:type=HelloWorld,name=helloworld,number=1");mBeanServer.registerMBean(bean, objectName);
?

注册完以后,只要程序没有退出,你就可以通过运行JConsole,选择对应的进程,看到你刚实现的MBean了。

?

?

2.动态MBean

?

动态MBean是通过实现DynamicMBean接口来实现的。还是实现一个如上的MBean类型,现在我们需要如下实现:

?

public class HelloWorldDynamicMBean implements DynamicMBean {public Object getAttribute(String attribute)throws AttributeNotFoundException, MBeanException,ReflectionException {return null;}public AttributeList getAttributes(String[] attributes) {return null;}public MBeanInfo getMBeanInfo() {MBeanAttributeInfo[] attris = new MBeanAttributeInfo[]{new MBeanAttributeInfo("age","int","The age of mine",true,false,false,null),new MBeanAttributeInfo("name","java.lang.String","The name of mine",true,true,false,null),new MBeanAttributeInfo("sex","boolean","Male or Female",true,false,true,null)};MBeanConstructorInfo[] constructs = new MBeanConstructorInfo[]{new MBeanConstructorInfo("HelloWorld", "The helloworld constructor", new MBeanParameterInfo[0])};MBeanOperationInfo[] opers = new MBeanOperationInfo[]{new MBeanOperationInfo("print", "Print result", new MBeanParameterInfo[0], "java.lang.String", MBeanOperationInfo.ACTION)};return new MBeanInfo("com.talend.liugang.jmx.HelloWorld", "HelloWorld Mbean", attris, constructs, opers, null);}public Object invoke(String actionName, Object[] params, String[] signature)throws MBeanException, ReflectionException {return null;}public void setAttribute(Attribute attribute)throws AttributeNotFoundException, InvalidAttributeValueException,MBeanException, ReflectionException {}public AttributeList setAttributes(AttributeList attributes) {return null;}}

?

这里剩下的很多方法我没有实现,其实主要的内容就在那个返回的MBeanInfo里,然后其他的方法都是对它的一个反馈,例如那些与Attribute相关的方法就是对我们MBeanInfo里定义的那些Attribute的操作;Invoke方法就是对MBeanInfo里定义的那些operation的操作。

?

剩下注册这个bean的方法和上面一样。

读书人网 >编程

热点推荐