jmx 实例--最简单的例子
1,接口
/** * standard MBeans, dynamic MBeans, open MBeans(形如MXBean) * and model MBeans,@MXBean()注解的接口名字可以任意取 * @author river.wang */@MXBean()public interface CMonitor0 { public long getUptime(); public String getMemory();}
?
?2,MBean,被管理对象,一如JavaBean。Bean对象,实体,对应资源。。。
/** * @author river.wang */public class ServerMonitor implements CMonitor0{ private final long startTime; private Runtime runtime = Runtime.getRuntime(); public ServerMonitor() { startTime = System.currentTimeMillis(); } public long getUptime() { return System.currentTimeMillis()-startTime; } public String getMemory() { float freeMemory = (float)runtime.freeMemory(); float totalMemory = (float)runtime.totalMemory(); String memory = "idle scale : "+(freeMemory/totalMemory)+"%; freeMemory=" +(freeMemory)/1024+" KB; totalMemory="+(totalMemory)/1024+" KB" ; return memory; }}
?
?3,运行下面程序,就可以用jconsole进行本地连接了
/** * @author river.wang */public class ServerMonitorAgent { public static void main( String[] args ) throws Exception { // MBeanServer server=MBeanServerFactory.createMBeanServer(); //不可在jconsole中使用 MBeanServer server = ManagementFactory.getPlatformMBeanServer();// 可在jconsole中使用 // 被管理的bean,"com.jmx"包名任意取 ObjectName monitorName = new ObjectName( "com.jmx:type=ServerMonitor" ); server.registerMBean( new ServerMonitor(), monitorName ); // 必须确保线程活着 Thread.sleep( Long.MAX_VALUE ); }}
?
?