---
title: "tomcat 7 源码分析-6 server初始化中的JMX(DynamicMBean)续"
author: "smartvessel"
date: "2010-07-20T18:01:53Z"
tags: []
categories: ["企业架构"]
slug: "tomcat-7-6-server-jmx-dynamicmbean"
draft: false
lastmod: "2010-07-20T18:07:06Z"
id: 717209
url: "https://smartvessel.iteye.com/blog/717209"
---

先说JMX，The JMX technology provides a simple, standard way of managing resources such as applications, devices, and services.

JMX是为了管理资源产生的，这个资源包括应用、设备和服务等。取个例子，如果你写了一个应用，初始化了20个的数据连接数，当你的应用还在跑的时候，发觉这个连接数少了，你要增加这个参数。JMX提供不需要停机，动态的管理连接数的方法。

先从简单的Standard MBeans看起。

通常我们先定义interface

第一步：MBean Interface

```
package com.example; 
 
public interface ConnectionNumberMBean { 
    public int getConnectionNumber(); 
    public void setConnectionNumber(int num); 
}
```

 第二步：实现接口

```
package com.example; 
import javax.management.*;
public class ConnectionNumber extends NotificationBroadcasterSupport implements ConnectionNumberMBean { 
 
    public int getConnectionNumber() { 
	return this.conNum ; 
    } 
 
    public synchronized void setConnectionNumber(int con_Num ) {

	this.conNum = con_Num ; 
 
	System.out.println("Connection number now " + this.conNum ); 
    } 
    private int conNum = DEFAULT_CON_Num;
    private static final int DEFAULT_CON_Num= 20; 
}
```

 第三步：创建a JMX Ageng来管理资源

```
package com.example;

import java.lang.management.ManagementFactory;
import javax.management.MBeanServer;
import javax.management.ObjectName;

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 Hello MBean we will register
	ObjectName mbeanName = new ObjectName("com.example:type=ConnectionNumber");

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

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

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

 编译生产Class文件后，运行它。

打开windows控制台，运行`jconsole命令，打开java控制台，如下图。`

![](http://dl.iteye.com/upload/picture/pic/67396/12e82b6f-d81f-3841-b407-393be536e5da.jpg)

可以看见我们注册的mian已经在列表上，可以连接

看下图，点MBean

![](http://dl.iteye.com/upload/picture/pic/67394/03762f11-4c20-3b5d-a751-6de3a75a6d4d.jpg)

![](/admin/blogs/d)

修改属性值，结果如下

![](http://dl.iteye.com/upload/picture/pic/67392/e881ebac-09a7-3059-b729-e279cdce3378.jpg)

![](/admin/blogs/d)