(转)JMX 入门例子

转自:http://rabbit9898.iteye.com/blog/1009198

 

   JMX(Java Management Extensions,即Java管理扩展)是一个为应用程序、设备、系统等植入管理功能的框架。JMX可以跨越一系列异构操作系统平台、系统体系结构和网络传输协议,灵活的开发无缝集成的系统、网络和服务管理应用。

 

  我们还是从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

 

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

 

Java代码 复制代码  收藏代码
  1. /* HelloMBean.java - MBean interface describing the management  
  2.    operations and attributes for the Hello World MBean.  In this case  
  3.    there are two operations, "sayHello" and "add", and two attributes,  
  4.    "Name" and "CacheSize". */  
  5.   
  6. package com.example.mbeans;   
  7.   
  8. public interface HelloMBean {   
  9.     // operations   
  10.   
  11.     public void sayHello();   
  12.     public int add(int x, int y);   
  13.   
  14.     // attributes   
  15.   
  16.     // a read-only attribute called Name of type String   
  17.     public String getName();   
  18.   
  19.     // a read-write attribute called CacheSize of type int   
  20.     public int getCacheSize();   
  21.     public void setCacheSize(int size);   
  22. }  
/* 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代码 复制代码  收藏代码
  1. /* Hello.java - MBean implementation for the Hello World MBean.  
  2.    因篇幅所限,把examples带的注释去掉了,自己可以下载看  */  
  3.   
  4. package com.example.mbeans;   
  5.   
  6. public class Hello implements HelloMBean {   
  7.     public void sayHello() {   
  8.     System.out.println("hello, world");   
  9.     }   
  10.   
  11.     public int add(int x, int y) {   
  12.     return x + y;   
  13.     }   
  14.   
  15.     public String getName() {   
  16.     return this.name;   
  17.     }   
  18.   
  19.      public int getCacheSize() {   
  20.     return this.cacheSize;   
  21.     }   
  22.   
  23.     public synchronized void setCacheSize(int size) {   
  24.     this.cacheSize = size;   
  25.   
  26.     System.out.println("Cache size now " + this.cacheSize);   
  27.     }   
  28.   
  29.     private final String name = "Reginald";   
  30.     private int cacheSize = DEFAULT_CACHE_SIZE;   
  31.     private static final int DEFAULT_CACHE_SIZE = 200;   
  32. }  
/* 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代码 复制代码  收藏代码
  1. package com.example.mbeans;   
  2.   
  3. import java.lang.management.*;   
  4. import javax.management.*;   
  5.   
  6. public class Main {   
  7.     /* For simplicity, we declare "throws Exception".  Real programs  
  8.        will usually want finer-grained exception handling.  */  
  9.     public static void main(String[] args) throws Exception {   
  10.     // Get the Platform MBean Server   
  11.     MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();   
  12.   
  13.     // Construct the ObjectName for the MBean we will register   
  14.     ObjectName name = new ObjectName("com.example.mbeans:type=Hello");   
  15.   
  16.     // Create the Hello World MBean   
  17.     Hello mbean = new Hello();   
  18.   
  19.     // Register the Hello World MBean   
  20.     mbs.registerMBean(mbean, name);   
  21.   
  22.     // Wait forever   
  23.     System.out.println("Waiting forever...");   
  24.     Thread.sleep(Long.MAX_VALUE);   
  25.     }   
  26. }  
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 连接 就可以进行管理了。

 


 

管理界面:

 



 
修改cacheSize 大小,可以在启动Main的命令行窗口看到修改生效。

 


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
下面是一个简单的 JMX 动态 MBean 的例子,该 MBean 可以动态地添加和移除属性、操作和通知等。 首先,需要实现 DynamicMBean 接口,定义 MBean 的属性、操作和通知等。下面是一个简单的实现: ```java public class SimpleDynamicMBean implements DynamicMBean { private Map<String, Object> attributes = new HashMap<String, Object>(); private Map<String, MBeanOperationInfo> operations = new HashMap<String, MBeanOperationInfo>(); private MBeanInfo mbeanInfo; public SimpleDynamicMBean() { // 初始化 MBean 的信息 init(); } // 初始化 MBean 的信息 private void init() { // 添加属性 attributes.put("name", "default"); attributes.put("age", 18); // 添加操作 MBeanParameterInfo[] params = new MBeanParameterInfo[] { new MBeanParameterInfo("name", String.class.getName(), "name of the person"), new MBeanParameterInfo("age", int.class.getName(), "age of the person") }; operations.put("setPerson", new MBeanOperationInfo("setPerson", "set person's name and age", params, void.class.getName(), MBeanOperationInfo.ACTION)); // 构建 MBean 的信息 mbeanInfo = new MBeanInfo(this.getClass().getName(), "SimpleDynamicMBean", null, null, operations.values().toArray(new MBeanOperationInfo[0]), null); } @Override public Object getAttribute(String attribute) throws AttributeNotFoundException, MBeanException, ReflectionException { if (!attributes.containsKey(attribute)) { throw new AttributeNotFoundException("Attribute " + attribute + " not found"); } return attributes.get(attribute); } @Override public void setAttribute(Attribute attribute) throws AttributeNotFoundException, InvalidAttributeValueException, MBeanException, ReflectionException { if (!attributes.containsKey(attribute.getName())) { throw new AttributeNotFoundException("Attribute " + attribute.getName() + " not found"); } attributes.put(attribute.getName(), attribute.getValue()); } @Override public AttributeList getAttributes(String[] attributes) { AttributeList resultList = new AttributeList(); for (String attribute : attributes) { try { Object value = getAttribute(attribute); resultList.add(new Attribute(attribute, value)); } catch (Exception e) { e.printStackTrace(); } } return resultList; } @Override public AttributeList setAttributes(AttributeList attributes) { AttributeList resultList = new AttributeList(); for (Object object : attributes) { Attribute attribute = (Attribute) object; try { setAttribute(attribute); String name = attribute.getName(); Object value = getAttribute(name); resultList.add(new Attribute(name, value)); } catch (Exception e) { e.printStackTrace(); } } return resultList; } @Override public Object invoke(String actionName, Object[] params, String[] signature) throws MBeanException, ReflectionException { if (!operations.containsKey(actionName)) { throw new IllegalArgumentException("Operation " + actionName + " not found"); } MBeanOperationInfo info = operations.get(actionName); return null; } @Override public MBeanInfo getMBeanInfo() { return mbeanInfo; } } ``` 在上面的实现中,我们定义了一个简单的 MBean,包括两个属性(name 和 age)和一个操作(setPerson)。在实现中,我们使用了一个 Map 来保存属性值,使用了一个 Map 来保存操作信息,同时也实现了 DynamicMBean 接口中的其他方法。 下面是一个简单的使用例子,演示如何动态地添加和移除属性、操作和通知等: ```java // 创建一个 MBeanServer MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); // 创建一个动态 MBean SimpleDynamicMBean mbean = new SimpleDynamicMBean(); // 将 MBean 注册到 MBeanServer 中 ObjectName name = new ObjectName("mydomain:type=SimpleDynamicMBean"); mbs.registerMBean(mbean, name); // 添加一个属性 mbean.addAttribute("gender", "male"); // 添加一个操作 MBeanParameterInfo[] params = new MBeanParameterInfo[] { new MBeanParameterInfo("gender", String.class.getName(), "gender of the person") }; mbean.addOperation("setGender", "set person's gender", params, void.class.getName(), MBeanOperationInfo.ACTION); // 移除一个属性 mbean.removeAttribute("gender"); // 移除一个操作 mbean.removeOperation("setGender"); // 销毁 MBean mbs.unregisterMBean(name); ``` 在上面的例子中,我们首先创建了一个 MBeanServer,然后创建了一个动态 MBean,并将其注册到 MBeanServer 中。接着,我们动态地添加和移除了一个属性和一个操作,最后销毁了该 MBean。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值