---
title: "（转）JMX 入门例子"
author: "haoppywang"
date: "2011-12-23T10:42:34Z"
tags: []
categories: ["编程语言"]
slug: "jmx"
draft: false
lastmod: "2011-12-23T10:42:34Z"
id: 1322373
url: "https://haoppywang.iteye.com/blog/1322373"
---

转自：[http://rabbit9898.iteye.com/blog/1009198](http://rabbit9898.iteye.com/blog/1009198)

 

   JMX（Java Management Extensions，即Java管理扩展）是一个为[应用程序](http://rabbit9898.iteye.com/view/330120.htm)、设备、系统等植入管理功能的框架。JMX可以跨越一系列异构[操作系统](http://rabbit9898.iteye.com/view/880.htm)平台、系统体系结构和[网络传输协议](http://rabbit9898.iteye.com/view/16807.htm)，灵活的开发无缝集成的系统、网络和服务管理应用。

 

　 我们还是从JMX能给我们提供什么好处入手来理解吧。举一个应用实例：在一个系统中常常会有一些配置信息，比如服务的IP地址，端口号什么的，那么如何来写这些代码呢？

1、初级程序员一般是写死在程序里，到要改变时就去改程序，然后再编译发布；

2、程序熟手则一般把这些信息写在一个配置文件里（JAVA一般都是\*.properties文件），  
    到要改变时只要改配置文件，但还是重新启动系统，以便读取配置文件里的新值；

3、程序好手则会写一个段代码，把配置值缓存起来，系统在读值的时候，先看看配置文件有  
    没有更动。如有更改则重读一遍，否则从缓存里读取值

4、程序高手则懂得取物为我所用，用JMX！把配置属性集中在一个类，然后写一个叫MBean  
    的东东，再配置一下就轻松搞定了。而且JMX自动提供了一个WEB页面来给你来改变这些  
    配置信息。

 

参考Java提供的例子（需要 jdk1.6）：

[http://download.oracle.com/javase/6/docs/technotes/guides/jmx/examples.html](http://download.oracle.com/javase/6/docs/technotes/guides/jmx/examples.html)

 

**1. 需要被管理类的接口  HelloMBean.java  （规范一般是\*\*\*MBean.java）**

 

Java代码 [![复制代码](/images/icon_copy.gif)](# "复制代码") [![收藏代码](/images/icon_star.png)![](/images/spinner.gif)]()

01. /* HelloMBean.java - MBean interface describing the management
02. operations and attributes for the Hello World MBean.  In this case
03. there are two operations, "sayHello" and "add", and two attributes,
04. "Name" and "CacheSize". \*/
05. **package** com.example.mbeans;
06. **public** **interface** HelloMBean {
07. // operations
08. **public** **void** sayHello();
09. **public** **int** add(**int** x, **int** y);
10. // attributes
11. // a read-only attribute called Name of type String
12. **public** String getName();
13. // a read-write attribute called CacheSize of type int
14. **public** **int** getCacheSize();
15. **public** **void** setCacheSize(**int** size);
16. }

```
/* HelloMBean.java - MBean interface describing the management
   operations and attributes for the Hello World MBean.  In this case
   there are two operations, "sayHello" and "add", and two attributes,
   "Name" and "CacheSize". */

package com.example.mbeans;

public interface HelloMBean {
    // operations

    public void sayHello();
    public int add(int x, int y);

    // attributes

    // a read-only attribute called Name of type String
    public String getName();

    // a read-write attribute called CacheSize of type int
    public int getCacheSize();
    public void setCacheSize(int size);
}
```

 

**2. 需要管理的类  Hello.java  （通常是实现\*\*MBean.java）**

Java代码 [![复制代码](/images/icon_copy.gif)](# "复制代码") [![收藏代码](/images/icon_star.png)![](/images/spinner.gif)]()

01. /* Hello.java - MBean implementation for the Hello World MBean.
02. 因篇幅所限，把examples带的注释去掉了，自己可以下载看  \*/
03. **package** com.example.mbeans;
04. **public** **class** Hello **implements** HelloMBean {
05. **public** **void** sayHello() {
06. System.out.println("hello, world");
07. }
08. **public** **int** add(**int** x, **int** y) {
09. **return** x + y;
10. }
11. **public** String getName() {
12. **return** **this**.name;
13. }
14. **public** **int** getCacheSize() {
15. **return** **this**.cacheSize;
16. }
17. **public** **synchronized** **void** setCacheSize(**int** size) {
18. **this**.cacheSize = size;
19. System.out.println("Cache size now " + **this**.cacheSize);
20. }
21. **private** **final** String name = "Reginald";
22. **private** **int** cacheSize = DEFAULT\_CACHE\_SIZE;
23. **private** **static** **final** **int** DEFAULT\_CACHE\_SIZE = 200;
24. }

```
/* Hello.java - MBean implementation for the Hello World MBean.
   因篇幅所限，把examples带的注释去掉了，自己可以下载看  */

package com.example.mbeans;

public class Hello implements HelloMBean {
    public void sayHello() {
	System.out.println("hello, world");
    }

    public int add(int x, int y) {
	return x + y;
    }

    public String getName() {
	return this.name;
    }

     public int getCacheSize() {
	return this.cacheSize;
    }

    public synchronized void setCacheSize(int size) {
	this.cacheSize = size;

	System.out.println("Cache size now " + this.cacheSize);
    }

    private final String name = "Reginald";
    private int cacheSize = DEFAULT_CACHE_SIZE;
    private static final int DEFAULT_CACHE_SIZE = 200;
}
```

 

 

**3. 代理/注册类 Main.java**

Java代码 [![复制代码](/images/icon_copy.gif)](# "复制代码") [![收藏代码](/images/icon_star.png)![](/images/spinner.gif)]()

01. **package** com.example.mbeans;
02. **import** java.lang.management.\*;
03. **import** javax.management.\*;
04. **public** **class** Main {
05. /* For simplicity, we declare "throws Exception".  Real programs
06. will usually want finer-grained exception handling.  \*/
07. **public** **static** **void** main(String\[] args) **throws** Exception {
08. // Get the Platform MBean Server
09. MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
10. // Construct the ObjectName for the MBean we will register
11. ObjectName name = **new** ObjectName("com.example.mbeans:type=Hello");
12. // Create the Hello World MBean
13. Hello mbean = **new** Hello();
14. // Register the Hello World MBean
15. mbs.registerMBean(mbean, name);
16. // Wait forever
17. System.out.println("Waiting forever...");
18. Thread.sleep(Long.MAX\_VALUE);
19. }
20. }

```
package com.example.mbeans;

import java.lang.management.*;
import javax.management.*;

public class Main {
    /* For simplicity, we declare "throws Exception".  Real programs
       will usually want finer-grained exception handling.  */
    public static void main(String[] args) throws Exception {
	// Get the Platform MBean Server
	MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();

	// Construct the ObjectName for the MBean we will register
	ObjectName name = new ObjectName("com.example.mbeans:type=Hello");

	// Create the Hello World MBean
	Hello mbean = new Hello();

	// Register the Hello World MBean
	mbs.registerMBean(mbean, name);

	// Wait forever
	System.out.println("Waiting forever...");
	Thread.sleep(Long.MAX_VALUE);
    }
}
```

 

**4. 编译、测试运行上面的程序**

 

javac com/example/mbeans/\*.java

\# 启动程序

java com.example.mbeans.Main

另起一个命令行或者cmd：

运行jconsole  （# JConsole is located in $(J2SE\_HOME)/bin/jconsole） 可以看到,选择本地的进程 com.example.mbeans 连接 就可以进行管理了。

 

![](http://dl.iteye.com/upload/attachment/467239/2f84be87-5195-3865-b8c1-204ff09358d7.png)

 

管理界面：

 

![](http://dl.iteye.com/upload/attachment/467243/35a413cf-fb27-340c-8b56-70db82879cd4.png "点击查看原始大小图片")  
   
修改cacheSize 大小，可以在启动Main的命令行窗口看到修改生效。

 

![](http://dl.iteye.com/upload/attachment/467248/ee220aa4-6c82-37bc-b93e-b68ad7852af4.png)