JMX 基础及实例

本文介绍JMX中动态MBeans的概念及其实现方式,并通过一个实战案例展示如何创建MBean接口及其实现类,最后通过客户端代码进行MBean的注册与管理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

JMX Java Management Extensions

Manageable resource:
可以被管理的资源可以是应用程序,设备或者存在的能够被java程序所访问或者包装的实体。通过JMX可以管理这些资源,应用程序能够暴露自己的组件,API或者附加的资源,使得JMX能够管理应用程序。
MBean Managed Bean
是一个java类 是符号jmx specification 所规定的命名和继承规范

[color=red] 动态 Mbeans 可在运行时定义属性和操作。这能力允许 Mbean 在装载时动态配置自己或根据它所处环境改变它的属性和操作[/color]


下面用一个案例来验证一下(是引用已经验证)
1.建立MBean
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.建立实现MBean的类


public class Hello implements HelloMBean{
private final String name = "Reginald";
private int cacheSize = DEFAULT_CACHE_SIZE;
private static final int DEFAULT_CACHE_SIZE = 200;


public int add(int x, int y) {
// TODO 自动生成方法存根
return x+y;
}

public int getCacheSize() {
// TODO 自动生成方法存根
return this.cacheSize;
}

public String getName() {
// TODO 自动生成方法存根
return this.name;
}

public void sayHello() {
// TODO 自动生成方法存根
System.out.println("hello,world");
}

public synchronized void setCacheSize(int size) {
// TODO 自动生成方法存根
this.cacheSize=size;
}

}
3.客户端代码
import java.lang.management.*;
import javax.management.*;

import com.sun.jdmk.*;
import com.sun.jdmk.comm.HtmlAdaptorServer;
public class Main {

/**
* @param args
* @throws NullPointerException
* @throws MalformedObjectNameException
* @throws NotCompliantMBeanException
* @throws MBeanRegistrationException
* @throws InstanceAlreadyExistsException
*/
public static void main(String[] args) throws MalformedObjectNameException, NullPointerException, InstanceAlreadyExistsException, MBeanRegistrationException, NotCompliantMBeanException {
// TODO 自动生成方法存根
MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
final HtmlAdaptorServer htmlAdaptor = new HtmlAdaptorServer();
final ObjectName htmlAdaptorON = new ObjectName("com.example.mbeans:name=HtmlAdaptor");
mbs.registerMBean(htmlAdaptor, htmlAdaptorON);
htmlAdaptor.setPort(9999);
System.out.print("Starting the HtmlAdaptor....");
htmlAdaptor.start();
}

}
[color=red]附这里如果没有在classpath中引入jdmkrt.jar 找不到com.sun.jdmk.comm.HtmlAdaptorServer[/color]

4.运行上面的java代码
控制台信息:Starting the HtmlAdaptor....
5.在浏览器中输入
http://localhost:9999/
这时候你就可以看见一个打开的网页,现在你就可以利用这个网页来进行MBean的管理了!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值