JMX之Model MBean

Model MBean同样也是动态MBeans,可以理解为这类MBean是基于一个基本的StandardMBean,并且完全可配置的,在运行期间进行自我声明;它们为资源动态工具提供一个一般性的,有默认行为的MBean类。

这个MBean的类不需要继承任何接口

package com.jmx.modelbean.demo;

public class Hello {//don't need implement interface
	
	private String name;
	
	public String getName() {
		return name;
	}
	
	public void printHello() {
		System.out.println("Hello World Model Bean......" + name);
	}
	
	public void printHello(String name) {
		System.out.println("Hello World Model Bean......." + name);
	}
	
	public void setName(String name) {
		this.name = name;
		System.out.println("My value is set to " + name);
	}
}

但是需要自己编写一个产生Model MBean的工具类,Model MBean使用JDK提供的RequiredModelMBean,指定基本bean(Hello),创建好需要的ModelMBeanInfo就可以了

package com.jmx.modelbean.demo;

import javax.management.Descriptor;
import javax.management.MBeanOperationInfo;
import javax.management.MBeanParameterInfo;
import javax.management.modelmbean.DescriptorSupport;
import javax.management.modelmbean.ModelMBeanAttributeInfo;
import javax.management.modelmbean.ModelMBeanInfo;
import javax.management.modelmbean.ModelMBeanInfoSupport;
import javax.management.modelmbean.ModelMBeanOperationInfo;
import javax.management.modelmbean.RequiredModelMBean;

public class ModelMBeanUtils {   
	private static final boolean READABLE = true; 
	private static final boolean WRITABLE = true; 
	private static final boolean BOOLEAN = true;   
	private static final String STRING_CLASS = "java.lang.String";   
	
	public static RequiredModelMBean createModelMBean() {   
		RequiredModelMBean model = null;   
		try {
			model = new RequiredModelMBean();
			//set Hello to ModelBean
			model.setManagedResource(new Hello(),"ObjectReference");
			
			//create mbean information
			ModelMBeanInfo info = createModelMBeanInfo();   
			model.setModelMBeanInfo(info);
			
		} catch (Exception e) {   
			e.printStackTrace();   
		}
		return model;   
	}

	private static ModelMBeanInfo createModelMBeanInfo() {

		//process exist attribute and method
		//create attribute of name
		Descriptor portAttrDesc = new DescriptorSupport();
        portAttrDesc.setField("name", "Name");
        portAttrDesc.setField("descriptorType", "attribute");
        portAttrDesc.setField("displayName", "Name");
        portAttrDesc.setField("getMethod", "getName");
        portAttrDesc.setField("setMethod", "setName");
		
        ModelMBeanAttributeInfo nameAttrInfo = new ModelMBeanAttributeInfo(//
                "Name", //attribute name
                STRING_CLASS, //attribute type
                "people name", //attribute desc
                READABLE, WRITABLE, !BOOLEAN,
                portAttrDesc //Descriptor
        );
        
        //getName
        Descriptor getStateDesc = new DescriptorSupport(new String[] {
          "name=getName", "descriptorType=operation", "class=com.jmx.modelbean.demo.Hello",
          "role=operation" });

        ModelMBeanOperationInfo getName = new ModelMBeanOperationInfo(//
          "getName", //
          "get name attribute", //
          null, //
          "java.lang.String", //
          MBeanOperationInfo.ACTION, //
          getStateDesc //
        );

        //setName
        Descriptor setStateDesc = new DescriptorSupport(new String[] {
          "name=setName", "descriptorType=operation", "class=com.jmx.modelbean.demo.Hello",
          "role=operation" });

        MBeanParameterInfo[] setStateParms = new MBeanParameterInfo[] { (new MBeanParameterInfo(
          "name", "java.lang.String", "new name value")) };

        ModelMBeanOperationInfo setName = new ModelMBeanOperationInfo(//
          "setName", //
          "set name attribute", //
          setStateParms, //
          "void", //
          MBeanOperationInfo.ACTION, //
          setStateDesc //
        ); 
        
		//create new method
		ModelMBeanOperationInfo print1Info = new ModelMBeanOperationInfo(
													"printHello",
													null,
													null,
													"void",
													MBeanOperationInfo.INFO,
													null);
		//create new method with params
		ModelMBeanOperationInfo print2Info;   
		MBeanParameterInfo[] param2 = new MBeanParameterInfo[1];   
		param2[0] = new MBeanParameterInfo("whoName", //param name
										STRING_CLASS, //param type
										"say hello to who");//param desc
		print2Info = new ModelMBeanOperationInfo(
							"printHello",
							null,
							param2,
							"void",
							MBeanOperationInfo.INFO,
							null);   
	
		//create ModelMBeanInfo          
		ModelMBeanInfo mbeanInfo = new ModelMBeanInfoSupport(//   
									RequiredModelMBean.class.getName(), //MBean
									null, //desc
									new ModelMBeanAttributeInfo[] { //attributes
										nameAttrInfo},
									null, //constructor
									new ModelMBeanOperationInfo[] { //operation
										getName,
										setName,
										print1Info, 
										print2Info},
									null, //notification
									null);//desc
		return mbeanInfo;   
	}   
}

在注册时没有什么特别之处,只是需要注意下通过工具类获得MBean即可

package com.jmx.modelbean.demo;

import java.lang.management.ManagementFactory;

import javax.management.InstanceAlreadyExistsException;
import javax.management.MBeanRegistrationException;
import javax.management.MBeanServer;
import javax.management.MalformedObjectNameException;
import javax.management.NotCompliantMBeanException;
import javax.management.ObjectName;
import javax.management.modelmbean.RequiredModelMBean;

import com.sun.jdmk.comm.HtmlAdaptorServer;

public class HelloAgent {
	public static void main(String[] args) throws MalformedObjectNameException, NullPointerException, InstanceAlreadyExistsException, MBeanRegistrationException, NotCompliantMBeanException {
		
		//create mbean server
		MBeanServer server = ManagementFactory.getPlatformMBeanServer();
		
		//create object name
		ObjectName helloName = new ObjectName("jmxMBean:name=hello");
		
		//receive ModelMBean by ModelMBeanUtils
		RequiredModelMBean hello = ModelMBeanUtils.createModelMBean();
		
		//create mbean and register mbean
		server.registerMBean(hello, helloName);
		
		//create adaptor, adaptor is just a form as show mbean. It has no relation to specific business mbean.
		HtmlAdaptorServer adaptor  = new HtmlAdaptorServer();
		//create adaptor name
		ObjectName adaptorName = new ObjectName("jmxAaptor:name=adaptor,port=5050");
		//register adaptor and adaptor name
		server.registerMBean(adaptor, adaptorName);
		
		adaptor.setPort(9999);
		adaptor.start();
		System.out.println("....................server start....................");
	}
}

Model MBean可以动态配置。试想一下这个应用场景:由于安全或其他原因,系统要把某个MBean公开的可管理方法隐藏起来。这时,如果你是用标准MBean,这需要修改接口类,然后重新编译发布;如果用 Apache commons-modeler(如果不想总要维护MBean这个借口,那么可以使用Apache的commons-modeler来辅助开发MBean,所有的MBean都装配在XML文件中)来写的模型MBean,则只需要修改XML文件就行了,不需要重新编译发布(可能要重启一下系统)。这就是Model Mbean 优势之所在了。
动态MBean和这一节的模型Mbean非常相似,但它们还是有很大不同的:动态MBean没有Hello类,它要自己实现Hello类中的方法逻辑。

JMX(Java Management Extensions)是Java平台的一个管理和监控API,可以让开发人员开发Mbean(Managed Bean)来管理和监控Java应用程序。Mbean是一种Java对象,通过JMX可以公开其属性和方法,以便对其进行管理和监控。 下面是一个简单的示例,演示如何使用JMX开发一个Mbean: 1. 定义一个实现了DynamicMBean接口的类,该类表示一个Mbean: ```java public class SimpleMBean implements DynamicMBean { private String name; public SimpleMBean(String name) { this.name = name; } @Override public Object getAttribute(String attribute) throws AttributeNotFoundException, MBeanException, ReflectionException { if (attribute.equals("Name")) { return name; } else { throw new AttributeNotFoundException(attribute); } } @Override public void setAttribute(Attribute attribute) throws AttributeNotFoundException, InvalidAttributeValueException, MBeanException, ReflectionException { throw new AttributeNotFoundException(attribute.getName()); } @Override public AttributeList getAttributes(String[] attributes) { AttributeList result = new AttributeList(); for (String attr : attributes) { try { result.add(new Attribute(attr, getAttribute(attr))); } catch (Exception ex) { // ignore } } return result; } @Override public AttributeList setAttributes(AttributeList attributes) { return new AttributeList(); } @Override public Object invoke(String actionName, Object[] params, String[] signature) throws MBeanException, ReflectionException { throw new ReflectionException(new NoSuchMethodException(actionName)); } @Override public MBeanInfo getMBeanInfo() { MBeanAttributeInfo[] attrs = new MBeanAttributeInfo[] { new MBeanAttributeInfo("Name", "java.lang.String", "name", true, false, false) }; MBeanConstructorInfo[] ctors = new MBeanConstructorInfo[] { new MBeanConstructorInfo("SimpleMBean()", "Default constructor", new MBeanParameterInfo[0]) }; return new MBeanInfo(getClass().getName(), "SimpleMBean", attrs, ctors, null, null); } } ``` 2. 创建一个MBeanServer对象,并将Mbean注册到MBeanServer中: ```java MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); ObjectName name = new ObjectName("com.example:type=SimpleMBean"); SimpleMBean mbean = new SimpleMBean("hello"); mbs.registerMBean(mbean, name); ``` 3. 使用JConsole或其他JMX客户端连接到MBeanServer,可以查看和修改Mbean的属性。 这是一个非常简单的示例,实际上,Mbean可以包含更复杂的逻辑和更多的属性。Mbean也可以使用注解来简化Mbean的开发和管理。JMX是一个强大的工具,可以帮助开发人员监控和管理Java应用程序。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值