JMX In Action 总结(二)--HelloWorld例子(一)

2014-11-24 00:41:26 · 作者: · 浏览: 2

这篇写一个简单的HelloWorld例子。
首先准备环境,我使用的JDK1.6,1.5应该也可以。还需要去oracle下载JMX RI包,地址为:http://www.oracle.com/technetwork/java/javase/tech/download-jsp-141676.html,下载“JMX 1.2 Reference Implementation”,解压以后lib目录下有两个jar包,把jmxtool.jar加到CLASSPATH中就可以了,它里面有一个接下去要用到的Html适配器。
1、首先写一个HelloWorld MBean,它由一个接口和一个实现类组成,代码如下:
public interface HelloWorldMBean {
public void setGreeting(String greeting);
public String getGreeting();
public void printGreeting();
}
写实现类HelloWorld:
public class HelloWorld implements HelloWorldMBean {

private String greeting = null;

public HelloWorld() {
this.greeting = "Hello World! I am a Standard MBean";
}

public HelloWorld(String greeting) {
this.greeting = greeting;
}

public void setGreeting(String greeting) {
this.greeting = greeting;
}

public String getGreeting() {
return greeting;
}

public void printGreeting() {
System.out.println(greeting);
}

}
这样,一个HelloWorld的MBean就完成了,这是一个标准MBean。必须把MBean注册到Agent才能使用,接下来写一个Agent。

2、定义JMX Agent:HelloAgent,他有三个任务:
1)、创建MBean Server实例。
2)、创建HTML适配器和HTML客户端连接。
3)、注册一个新的HelloWorld的MBean实例。
代码如下:
public class HelloAgent {

private MBeanServer mbs = null;

public HelloAgent() {
mbs = MBeanServerFactory.createMBeanServer("HelloAgent");

HtmlAdaptorServer adapter = new HtmlAdaptorServer();
HelloWorld hw = new HelloWorld();
ObjectName adapterName = null;
ObjectName helloWorldName = null;
try {
helloWorldName = new ObjectName("HelloAgent:name=helloWorld1");
mbs.registerMBean(hw, helloWorldName);
adapterName = new ObjectName("HelloAgent:name=htmladapter,port=9092");
adapter.setPort(9092);
mbs.registerMBean(adapter, adapterName);
adapter.start();
} catch (Exception e) {
e.printStackTrace();
}
}

public static void main(String args[]) {
System.out.println("HelloAgent is running");
HelloAgent agent = new HelloAgent();
}
}
这段代码首先创建一个MBean Server实例和一个Html适配器实例,MBean Server使用工厂类创建,创建的时候传入字符串作为MBean Server的域名,域名是区别MBean Server的标识。
接下来实例化HelloWorld MBean,并在MBean Server中注册。注册的时候使用一个ObjectName实例,ObjectName类在JMX中为MBean提供了一套命名系统,是注册在MBean Server中的唯一标识。它有两部分组成:
1)、域名:这个域名通常和MBean Server的域名一致,如果不一致,则意味着与其他MBean隔离。
2)、零个或多个key=value串,中间用逗号隔开,这个串用来区别MBean,也可以为MBean提供信息。
下一步是注册Html适配器,Html适配器也是一个MBean,并启动适配器。

以上两步就是我们例子的代码,基本结构图如下:
\


3、运行例子。HelloAgent类有main方法,直接运行就可以了,如果成功就会出现“HelloAgent is running”。然后打开浏览器,输入:http://localhost:9092/,因为代码中Html的适配器端口设置为9092。

以上3步完成了整个HelloWorld例子,通过浏览器提供了3种页面:
1、Agent页面,也就是第一个看到的页面,上面Agent内包含的MBean的一个总览,它显示了所有的注册在里面的MBean,通过注册时候使用的ObjectName实例来显示。可以通过最上面的文本框来过滤需要显示的MBean。
2、MBean页面,点击Agent页面中的某个MBean可以进入该MBean页面。我们点击第一个name=helloWorld1的MBean,显示有一下几个信息:
a)、MBean注册时提供的ObjectName,HelloAgent:name=helloWorld1
b)、类的名字,在这个例子中是HelloWorld。
c)、描述,对于Stand MBean,描述有MBean Server创建。
d)、属性列表,MBean暴露的属性列表,这个MBean有一个属性Greeting是个可读写属性(RW,因为有getter和setter),你可以在Value列的文本框中输入字符串,点击Apply,就动态设置了Greeting的值。
e)、暴露的操作列表,这个MBean有一个操作printGreeting,点击printGreeting按钮可