从零开始玩转JMX(四)——Apache Commons Modeler & Dynamic MBean
Apache Commons Modeler
前面的Model MBean的创建方式看上去特别复杂,一个简单功能的类ModelMBeanUtils 写了很多代码,那有木有简单点的方式呢,答案是肯定的,这里就引出了Apache Commons Modeler(使用这个需要在classpath中导入commons-modeler-2.0.1.jar以及modeler的依赖项目commons-logging-1.1.3.jar,下载地址:http://commons.apache.org/proper/commons-modeler/download_modeler.cgi),使用Apache的Moleler库创建Model MBean最大帮助是,我们不需要再写复杂的代码来创建ModelMBeanInfo对象了。只需要一个MBean描述符(实际上就是一个xml配置文件,Apache Commons Modeler将ModelMBeanUtils 复杂的创建过程转移到xml中来配置,然后自身模块创建对象代替ModelMBeanUtils 的功能,简化用户的操作)来对Model MBean进行描述,就可以轻松的创建Model MBean.
下面来讲前面的Hello.java和HelloAgent.java的例子采用Apache Commons Modele进行改造。
首先还是Hello.java,和Model MBean中的一样,没有implements任何接口。
package com.test.jmx.modeler;
public class Hello{
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name= name;
}
public void printHello() {
System.out.println("Hello World, "+name);
}
public void printHello(String whoName) {
System.out.println("Hello, "+whoName);
}
}
接下去就是最关键的描述文件(mbeans-descriptors.xml)了:
<?xml version="1.0" encoding="UTF-8" ?>
<mbeans-descriptors>
<mbean name="Hello" description="the hello bean" domain="MyMBean" group="helloGroup" type="com.test.jmx.modeler.Hello">
<attribute name="name" description="a name attribute" type="java.lang.String" writeable="true"/>
<operation name="printHello" description="public void printHello()" impact="ACTION" returnType="void"/>
<operation name="printHello" description="public void printHello(String whoName)" impact="ACTION" returnType="void">
<parameter name="whoName" description="method parameter of printHello" type="java.lang.String"></parameter>
</operation>
</mbean>
</mbeans-descriptors>
描述文件的名字可以随意,最主要的是要和下面的HelloAgent.java对应起来。
通过这个xml文件的定义就描述了Model MBean所需要的metadata信息和一个基本的ModelMBean实现。
关于这个xml文件有几个需要说明的地方:
<mbean>的属性classname,name,type:
- name属性是每个MBean被Registry对象注册的对象名
- type属性是真正被管理资源的全面(包括包名)
- classname属性是用户扩展的用于实现代理功能的Model MBean的全名,如果不提供Modeler会使用BaseModelMBean;如果提供了代理的ModelMBean对象,在使用时可以使用如下的代码样本访问他所代理的资源对象。
其余的标签就比较好理解了。综述:上面所示代码声明了一个Model MBean, 唯一标示是“Hello”,该MBean负责管理的对象是com.test.jmx.modeler.Hello的实例。域是MyMBean。这个MBean暴露了一个属性name和两个方法printHello()和printHello(String whoName).
下面是新的HelloAgent.java的代码:
package com.test.jmx.modeler;
import com.sun.jdmk.comm.HtmlAdaptorServer;
import org.apache.commons.modeler.ManagedBean;
import org.apache.commons.modeler.Registry;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import javax.management.modelmbean.ModelMBean;
import java.io.InputStream;
public class HelloAgent {
public static void main(String[] args) throws Exception {
// 需要将xml信息读入到Registry对象中
Registry registry = Registry.getRegistry(null,null);
InputStream stream = HelloAgent.class.getResourceAsStream("mbeans-descriptors.xml");
registry.loadMetadata(stream);
MBeanServer server = registry.getMBeanServer();
// 之前是:MBeanServer server = ManagementFactory.getPlatformMBeanServer();
ManagedBean managed = registry.findManagedBean("Hello");
ObjectName helloName = new ObjectName(managed.getDomain()+":name=HelloWorld");
// 以前是Hello hello = new Hello(); 为什么要多个createMBean?因为现在的写法没有写MBean,所以才要动态生成一个,以前就直接
// 把new hello()注册到MBeanServer就可以了,server会自动找到它的HelloMBean接口文件。
ModelMBean hello = managed.createMBean(new Hello());
server.registerMBean(hello,helloName);
ObjectName adapterName = new ObjectName(managed.getDomain()+":name = htmladapter,port=8082");
HtmlAdaptorServer adapter = new HtmlAdaptorServer();
server.registerMBean(adapter,adapterName);
adapter.start();
}
}
注意这里的Registry是指org.apache.commons.modeler.Registry,因为JMX自身也有一个Registry(java.rmi.registry.Registry)。通过Modeler组件提供的Registry对象,可以很方便的完成MBeanServer的创建。
运行效果和之前的一样,这里就不赘述了,有兴趣的小伙伴可以试一下。
Dynamic MBean
四种类型的MBean,前面所讲的都是常用的,现在还剩两种Open MBean就不讲述了,这里简单记录下Dynamic MBean。
Dynamic MBean不需要自定义MBean接口,只需要实现DynamicMBean接口即可,Dynamic MBean没有任何明显些在代码里的属性和方法,所有的属性和方法都是通过反射结合JMX提供的辅助元数据从而动态生成。
下面的代码中首先定义了一个属性name和一个方法print,之后在管理界面(localhost:8082)中点击print之后生成一个print1的方法。
Dynamic MBean的代码如下:
package com.test.jmx.DynamicMBean;
import javax.management.*;
import java.lang.reflect.Constructor;
import java.util.Iterator;
/**
* Created by hidden on 2016/10/9.
*/
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;
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);
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);
}
public HelloDynamic(){
init();
buildDynamicMBean();
}
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);
}
@Override
public Object getAttribute(String attribute) throws AttributeNotFoundException, MBeanException, ReflectionException {
if (attribute == null) {
return null;
}
if (attribute.equals("Name")) {
return name;
}
return null;
}
@Override
public void setAttribute(Attribute attribute) throws AttributeNotFoundException, InvalidAttributeValueException, MBeanException, ReflectionException {
if (attribute == null) {
return;
}
String Name = attribute.getName();
Object value = attribute.getValue();
try {
if (Name.equals("Name")) {
if (value == null) {
name=null;
} else if (Class.forName("java.lang.String").isAssignableFrom(value.getClass())) {
name = (String) name;
}
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
@Override
public AttributeList getAttributes(String[] attributes) {
if (attributes == null) {
return null;
}
AttributeList resultList = new AttributeList();
// if (attributes.length == 0) {
// return resultList;
// }
for(int i=0;i<attributes.length;i++){
try {
Object value = getAttribute(attributes[i]);
resultList.add(new Attribute(attributes[i],value));
} catch (AttributeNotFoundException e) {
e.printStackTrace();
} catch (MBeanException e) {
e.printStackTrace();
} catch (ReflectionException e) {
e.printStackTrace();
}
}
return resultList;
}
@Override
public AttributeList setAttributes(AttributeList attributes) {
if (attributes == null) {
return null;
}
AttributeList resultList = new AttributeList();
if(attributes.isEmpty()){
return resultList;
}
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 (AttributeNotFoundException e) {
e.printStackTrace();
} catch (InvalidAttributeValueException e) {
e.printStackTrace();
} catch (MBeanException e) {
e.printStackTrace();
} catch (ReflectionException e) {
e.printStackTrace();
}
}
return resultList;
}
@Override
public Object invoke(String actionName, Object[] params, String[] signature) throws MBeanException, ReflectionException {
if(actionName.equals("print")){
System.out.println("Hello, "+name+",this is HelloDynamic!");
dynamicAddOperation();
return null;
}else if(actionName.equals("print1")){
System.out.println("这是动态增加的一个方法print1");
return null;
}else {
throw new ReflectionException(new NoSuchMethodException(actionName),"Cannot find the operation "+actionName+" in "+className);
}
}
@Override
public MBeanInfo getMBeanInfo() {
return mBeanInfo;
}
}
通过Agent调用Dynamic MBean:
package com.test.jmx.DynamicMBean;
import com.sun.jdmk.comm.HtmlAdaptorServer;
import javax.management.*;
import java.lang.management.ManagementFactory;
import java.util.concurrent.TimeUnit;
public class HelloAgent {
public static void main(String[] args) throws MalformedObjectNameException, NotCompliantMBeanException, InstanceAlreadyExistsException, MBeanRegistrationException {
MBeanServer server = ManagementFactory.getPlatformMBeanServer();
ObjectName helloName = new ObjectName("MyMBean:name=helloDynamic");
HelloDynamic hello = new HelloDynamic();
server.registerMBean(hello,helloName);
ObjectName adapterName = new ObjectName("MyMBean:name=htmladapter");
HtmlAdaptorServer adapter = new HtmlAdaptorServer();
server.registerMBean(adapter,adapterName);
adapter.start();
}
}
运行效果图如下:
运行结果:
Hello, null,this is HelloDynamic!
这是动态增加的一个方法print1
wanna more?
1. 从零开始玩转JMX(一)——简介和Standard MBean
2. 从零开始玩转JMX(二)——Condition
3. 从零开始玩转JMX(三)——Model MBean
4. 从零开始玩转JMX(四)——Apache Commons Modeler & Dynamic MBean
参考资料
从零开始玩转JMX(四)——Apache Commons Modeler & Dynamic MBean的更多相关文章
- 从零开始玩转JMX(一)——简介和Standard MBean
JMX的全称为Java Management Extensions. 顾名思义,是管理Java的一种扩展.这种机制可以方便的管理.监控正在运行中的Java程序.常用于管理线程,内存,日志Level,服 ...
- 从零开始玩转JMX(三)——Model MBean
Model MBean 相对于Standard MBean,Model MBean更加灵活.如果我们不能修改已有的Java类,那么使用Model MBean是不错的选择. Model MBean也是一 ...
- 从零开始玩转JMX(二)——Condition
Notification 一个MBean提供的管理接口允许代理对其管理资源进行控制和配置.然而,对管理复杂的分布式系统来说,这些接口知识提供了一部分功能.通常,管理应用程序需要对状态变化或者当特别情况 ...
- Failed to unregister the JMX name: org.apache.commons.dbcp2:name=xxx,type=BasicDataSource
把datesource的bean的class由 org.apache.commons.dbcp2.BasicDataSource 改成 org.apache.tomcat.dbcp.dbcp.Basi ...
- Java (四)APACHE Commons IO 复制文件
上一篇:Java (三)APACHE Commons IO 常规操作 例1:复制文件 1 import java.io.File; 2 import java.io.IOException; 3 4 ...
- apache commons Java包简介
更多信息,请参考:http://commons.apache.org/ 一.Commons BeanUtils说明:针对Bean的一个工具集.由于Bean往往是有一堆get和set组成,所以BeanU ...
- 一篇关于apache commons类库的详解
1.1. 开篇 在Java的世界,有很多(成千上万)开源的框架,有成功的,也有不那么成功的,有声名显赫的,也有默默无闻的.在我看来,成功而默默无闻的那些框架值得我们格外的尊敬和关注,Jakarta C ...
- 一篇关于apache commons类库的详解[转]
1.1. 开篇 在Java的世界,有很多(成千上万)开源的框架,有成功的,也有不那么成功的,有声名显赫的,也有默默无闻的.在我看来,成功而默默无闻的那些框架值得我们格外的尊敬和关注,Jakarta C ...
- apache commons类库的学习
原文地址http://www.tuicool.com/articles/iyEbquE 1.1. 开篇 在Java的世界,有很多(成千上万)开源的框架,有成功的,也有不那么成功的,有声名显赫的,也有默 ...
随机推荐
- 解决64位debian下无法安装ia32库的问题
原文地址:http://crunchbang.org/forums/viewtopic.php?pid=277918 因为64位debian源中并没有包括32位的软件包,所提安装ia32会提示依赖无法 ...
- php中var_dump、var_export和print_r的用法区别
void var_dump ( mixed $expression [, mixed $... ] )此函数显示关于一个或多个表达式的结构信息,包括表达式的类型与值.数组将递归展开值,通过缩进显示其结 ...
- PHP_OS常量使用方法
通过PHP_OS来获得当前运行的操作系统,如果直接使用将无法获取值,但有一些默认的值,使用方法如下: switch(PHP_OS) { case 'FreeBSD': ...
- 【Unity Shader编程】之十六 基于MatCap实现适于移动平台的“次时代”车漆Shader
本系列文章由@浅墨_毛星云 出品,转载请注明出处. 文章链接:http://blog.csdn.net/poem_qianmo/article/details/55803629 渲染本文配图使用的 ...
- Swift 语言附注 类型
本页包括内容: 类型注解(Type Annotation) 类型标识符(Type Identifier) 元组类型(Tuple Type) 函数类型(Function Type) 数组类型(Array ...
- 2.AS入门教程
AndroidStudio 本文是关于androidStudio的一些基础知识 介绍 Google官方的Android集成开发环境(IDE = Integrated Development Envir ...
- R语言 dbWriteTable 写入数据库 为空和乱码问题
在windows环境下 用RMySQL 写入数据库中文数据为空 或者乱码问题. 找了下资料 一般情况是 用 insert 语句插入,结合现有业务有点麻烦,放弃了. 还有一种方式换平台,由于经常在win ...
- MongoDB主从复制+集群
一.读写分离的概念 读写分离,基本的原理是让主数据库处理事务性增.改.删操作(INSERT.UPDATE.DELETE),而从数据库处理SELECT查询操作.数据库复制被用来把事务性操作导致的变更同步 ...
- mysql数据库从删库到跑路之mysql完整性约束
一 介绍 约束条件与数据类型的宽度一样,都是可选参数 作用:用于保证数据的完整性和一致性主要分为: PRIMARY KEY (PK) 标识该字段为该表的主键,可以唯一的标识记录 FOREIGN KEY ...
- nginx 413文件上报太大
在nginx使用过程中,上传文件的过程中,通常需要设置nginx报文大小限制.避免出现413 Request Entity Too Large. 于是奇葩的问题被我们遇到了,详细配置请参考下面.我们的 ...