`
liyiye
  • 浏览: 421553 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类
最新评论

4、动态MBean:DynamicMBean

    博客分类:
  • jmx
阅读更多

一、前言

 

  动态MBean是在运行期才定义它的属性和方法,也就是说它有什么属性和方法是可以动态改变的。动态MBean主要利用一些辅助类(构造函数类MBeanConstructorInfo、属性类MBeanAttributeInfo、方法类MBeanOperationInfo)来完成这个功能,所有的动态MBean必须实现DynamicMBean接口。DynamicMBean写好后,使用方法和第一篇文章中普通的MBean一样。

 

  给出一个动态MBean的实例,这个实例最初动态构了一个Name属性及一个print方法,当我们执行它的print方法之后,又给此MBean新增了一个print1方法。实例的代码如下:

二、实例

1HelloDynamic

import java.lang.reflect.Constructor;
import java.util.Iterator;
import javax.management.Attribute;
import javax.management.AttributeList;
import javax.management.DynamicMBean;
import javax.management.MBeanAttributeInfo;
import javax.management.MBeanConstructorInfo;
import javax.management.MBeanException;
import javax.management.MBeanInfo;
import javax.management.MBeanNotificationInfo;
import javax.management.MBeanOperationInfo;
import javax.management.MBeanParameterInfo;
import javax.management.ReflectionException;

/**
 * @author Sunny Peng
 * @author change by Chen.Gang, add a feature for dynamic add operation
 * @version 1.0
 */
public class HelloDynamic implements DynamicMBean {
    //
这是我们的属性名称
    private String name;
    private MBeanInfo mBeanInfo = null;
    private String className;
    private String description;
    private MBeanAttributeInfo[] attributes;
    private MBeanConstructorInfo[] constructors;
    private MBeanOperationInfo[] operations;
    MBeanNotificationInfo[] mBeanNotificationInfoArray;

    public HelloDynamic() {
        init();
        buildDynamicMBean();
    }

    private void init() {
        className = this.getClass().getName();
        description = "Simple implementation of a dynamic MBean.";
        attributes = new MBeanAttributeInfo[1];
        constructors = new MBeanConstructorInfo[1];
        operations = new MBeanOperationInfo[1];
        mBeanNotificationInfoArray = new MBeanNotificationInfo[0];
    }

    private void buildDynamicMBean() {
        //
设定构造函数
        Constructor[] thisconstructors = this.getClass().getConstructors();
        constructors[0] = new MBeanConstructorInfo("HelloDynamic(): Constructs a HelloDynamic object", thisconstructors[0]);
        //
设定一个属性
        attributes[0] = new MBeanAttributeInfo("Name", "java.lang.String", "Name: name string.", true, true, false);
        //operate method
我们的操作方法是print
        MBeanParameterInfo[] params = null;//
无参数

        operations[0] = new MBeanOperationInfo("print", "print(): print the name", params, "void", MBeanOperationInfo.INFO);
        mBeanInfo = new MBeanInfo(className, description, attributes, constructors, operations, mBeanNotificationInfoArray);
    }

    //动态增加一个print1方法
    private void dynamicAddOperation() {
        init();
        operations = new MBeanOperationInfo[2];//
设定数组为两个
        buildDynamicMBean();
        operations[1] = new MBeanOperationInfo("print1", "print1(): print the name", null, "void", MBeanOperationInfo.INFO);
        mBeanInfo = new MBeanInfo(className, description, attributes, constructors, operations, mBeanNotificationInfoArray);
    }

    public Object getAttribute(String attribute_name) {
        if (attribute_name != null)
            return null;
        if (attribute_name.equals("Name"))
            return name;
        return null;
    }

    public void setAttribute(Attribute attribute) {
        if (attribute == null)
            return;
        String Name = attribute.getName();
        Object value = attribute.getValue();
        try {
            if (Name.equals("Name")) {
                // if null value, try and see if the setter returns any exception
                if (value == null) {
                    name = null;
                    // if non null value, make sure it is assignable to the attribute
                } else if ((Class.forName("java.lang.String")).isAssignableFrom(value.getClass())) {
                    name = (String) value;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public AttributeList getAttributes(String[] attributeNames) {
        if (attributeNames == null)
            return null;
        AttributeList resultList = new AttributeList();
        // if attributeNames is empty, return an empty result list
        if (attributeNames.length == 0)
            return resultList;
        for (int i = 0; i < attributeNames.length; i++) {
            try {
                Object value = getAttribute(attributeNames[i]);
                resultList.add(new Attribute(attributeNames[i], value));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return resultList;
    }

    public AttributeList setAttributes(AttributeList attributes) {
        if (attributes == null)
            return null;
        AttributeList resultList = new AttributeList();
        // if attributeNames is empty, nothing more to do
        if (attributes.isEmpty())
            return resultList;
        // for each attribute, try to set it and add to the result list if successfull
        for (Iterator i = attributes.iterator(); i.hasNext();) {
            Attribute attr = (Attribute) i.next();
            try {
                setAttribute(attr);
                String name = attr.getName();
                Object value = getAttribute(name);
                resultList.add(new Attribute(name, value));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return resultList;
    }

    public Object invoke(String operationName, Object params[], String signature[]) throws MBeanException, ReflectionException {
        // Check for a recognized operation name and call the corresponding operation
        if (operationName.equals("print")) {
            //
具体实现我们的操作方法print
            System.out.println("Hello, " + name + ", this is HellDynamic!");
            dynamicAddOperation();
            return null;
        } else if (operationName.equals("print1")) {
            System.out.println("
这是动态增加的一方法
print1");
            return null;
        } else {
            // unrecognized operation name:
            throw new ReflectionException(new NoSuchMethodException(operationName), "Cannot find the operation " + operationName + " in " + className);
        }

    }

    public MBeanInfo getMBeanInfo() {
        return mBeanInfo;
    }
}

 

说明:

·         实现于接口DynamicMBean

·         借助于各种辅助类完成一个类的构造。构造函数类MBeanConstructorInfo、属性类MBeanAttributeInfo、方法类MBeanOperationInfo

·         这里所有public方法是实现于DynamicMBean的。主要提供:setAttribute设置属性、getAttribute取得属性、setAttributes设置一组属性、getAttributes取得一组属性、invoke方法调用、getMBeanInfo MBeanServer由这个方法得到关键的MBean类的构造信息。

2HelloAgent

  

  前面说了HelloDynamic和普通MBean的使用方法是一样的,因此HelloAgent和第一篇的HelloAgent基本一样,就是把Hello改成HelloDynamic而已。为了实例完整,也一并帖出来吧。

import javax.management.MBeanServerFactory;
import javax.management.ObjectName;
import com.sun.jdmk.comm.HtmlAdaptorServer;
public class HelloAgent {
    public static void main(String[] args) throws Exception {
        MBeanServer server = MBeanServerFactory.createMBeanServer();
        ObjectName helloName = new ObjectName("chengang:name=HelloDynamic");
        HelloDynamic hello = new HelloDynamic();
        server.registerMBean(hello, helloName);
        ObjectName adapterName = new ObjectName("HelloAgent:name=htmladapter,port=8082");
        HtmlAdaptorServer adapter = new HtmlAdaptorServer();
        server.registerMBean(adapter, adapterName);
        adapter.start();
        System.out.println("start.....");
    }
}

 

3、运行

 

  先运行HelloAgent。再打开浏览器,输入网址:http://localhost:8082/。单击进入name=HelloDynamic项,执行print方法后再回到上一页面你会发现又多了一个print1方法。

 

4、总结

  动态MBean的代码稍显复杂,但对于一些特殊需求的情况,它将显示出强大威力。而且它还是模型MBeansModel MBeans)的基础。不过在一般的项目中,动态MBean还是用得比较少,所谓利器深藏之而不用,非常时方现光芒。

 

 

分享到:
评论

相关推荐

    hellombean.zip_zip

    `DynamicMBean`接口是所有动态MBean的基类,通过实现这个接口,可以动态地提供MBean的操作和属性。 3. 开放MBean:开放MBean是一种特殊的动态MBean,它的属性和操作都遵循一种标准的数据类型,这使得它们可以被任何...

    JMX IN ACTION(五)

    在第四章中我们了解到,MBean不能同时实现自己的MBean接口和DynamicMBean接口,这确保了MBean不能同时是标准和动态的。DynamicMBean接口是一个预定义的标准接口,它允许MBean在运行时描述其管理接口。一个MBean的...

    面试官问我 JMX 了解不,我说:什么? - 知乎1

    4. **Model MBean**:是Dynamic MBean的一种增强,它提供了一种模型化的方式,允许将任何Java对象封装为MBean,而无需直接实现`DynamicMBean`接口。Model MBean通过实现`javax.management.modelmbean.ModelMBeanInfo...

    jmx 入门文档,附有开发实例文档

    2. **动态MBean**:动态MBean不强制实现特定的MBean接口,而是实现`DynamicMBean`接口,它提供了运行时动态暴露属性和操作的能力。 3. **模型MBean**:模型MBean通过元数据描述其属性、操作和通知,这样可以更灵活...

    JMX in Action

    - **动态 MBean**: 实现 `DynamicMBean` 接口的 MBean,可以动态地添加和删除属性及操作。 2. **MBean 属性**: MBeans 可以包含多种属性,这些属性可以被外部系统读取或修改。 3. **MBean 操作**: MBeans 还可以...

    jmxtools-1.2 jmxri jar

    5. **Standard MBeans and Dynamic MBeans**:提供了一套标准的MBean实现,以及动态MBean(DynamicMBean)接口,后者允许对象在运行时自定义其管理接口。 6. **Other Utilities**:可能还包括其他的辅助类和接口,...

    JMX IN ACTION(七)

    `RequiredModelMBean`类实现了`ModelMBean`接口,而`ModelMBean`接口扩展了`DynamicMBean`接口。但是,与常规Dynamic MBeans不同,Model MBean的管理接口是由管理应用程序或资源外部定义,并通过setter方法插入到...

    jmx学习整理里1

    2. Dynamic MBeans:也称为DynamicMBean,它们不依赖于预先定义的接口,而是通过`javax.management.DynamicMBean`接口提供动态暴露管理信息。这种类型的MBean更灵活,可以在运行时改变其管理属性和操作。 3. Model ...

    JMX小例子以及介绍

    **4. JMX实践** 在实际应用中,JMX常用于监控复杂的系统和服务,如Spring框架就利用JMX暴露其内部管理接口。例如,你可以通过JMX监控和调整Spring应用上下文中的bean。 **5. 结论** JMX为Java开发者提供了一种...

    JMX: Developer's Quick Start Guide

    - **Dynamic MBeans**:动态MBeans允许在运行时动态地改变其操作和属性集合。它们通过实现`javax.management.DynamicMBean`接口来创建。这类MBean更加灵活,适合于需要在运行时动态调整的应用场景。 - **Model ...

    Jmx实例demo下载

    4. **MBean操作**:在MBean中定义的操作可以通过JMX客户端调用,这些操作可能包括获取状态信息、执行管理任务等。 5. **JMX连接器**:`jmxdemo`可能包含了JMX连接器的配置,如RMI连接器,允许远程客户端连接到MBean...

    java实现简单远程监控

    2. **实现MBean接口**:MBean类需要实现 javax.management.DynamicMBean 接口或者继承 StandardMBean 类,以便符合JMX规范。 3. **注册MBean**:创建MBeanServer实例,并将MBean注册到MBeanServer中,这样MBean就可...

    Java Management Extensions管理扩展原理解析

    4. **操作MBean**:通过MBean服务器,管理者可以调用MBean的方法,获取或设置属性,以及执行其他管理操作。 JMX通过提供标准接口和组件,使得开发者能够轻松地在Java应用中集成管理功能。无论是简单的日志记录、...

    Java Management Extensions

    这通常涉及到实现`DynamicMBean`接口,该接口提供了一组方法来创建和销毁属性。 ##### 4.3 模型MBeans 模型MBeans提供了最高的灵活性,适用于那些需要自定义属性和操作的对象。实现模型MBeans通常需要使用`Model...

    SpringJMX.pdf

    - **配置管理**:动态调整应用程序配置,无需重启服务。 - **故障诊断**:收集异常信息和堆栈跟踪,帮助快速定位问题。 #### 九、总结 通过本次讨论,我们深入了解了**软件监控与管理**的重要性,学习了**JMX**的...

    jmx 监控 tomcat

    这通常涉及实现`javax.management.MBean`接口或继承`javax.management.DynamicMBean`类,并使用`StandardMBean`包装器。 7. **JMX通知** JMX还支持发布和订阅通知,使得在特定事件发生时,客户端可以收到通知。...

    MSM101_1_3_Services

    SPI允许Java应用程序在运行时动态发现和使用服务,这是通过在`META-INF/services`目录下放置配置文件来实现的。例如,如果你有一个服务接口`com.example.MyService`,任何实现该接口的类都可以通过在`META-INF/...

Global site tag (gtag.js) - Google Analytics