在jdk1.5中提供了新的工具jconsole可以用于观察程序运行等情况,对于jmx来说jconsole能够在图形界面下查看mbean的属性和操作方法,这样就不必另外增加HtmlAdaptorServer来查看了 :) .
让我们来看下代码就知道了。(HelloMBean.java和Hello.java和原来的没什么变动)
HelloMBean.java
/*
* Created on 2005-3-17
* @Author roson
*
*/
package bean;
public interface HelloMBean {
public void sayHello();
public String getMessage();
public void setMessage(String message);
public int getChangeCount();
public void resetCounter();
}
Hello.java
/*
* Created on 2005-3-17
* @Author roson
*
*/
package bean;
import javax.management.*;
public class Hello extends NotificationBroadcasterSupport implements HelloMBean{
private String message;
private int changeCount;
private long sequenceNumber=1;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
changeCount++;
Notification notification=new Notification("bean/hello",
this,
sequenceNumber++,
System.currentTimeMillis(),
message);
sendNotification(notification);
}
public int getChangeCount() {
return changeCount;
}
public void resetCounter()
{
changeCount=0;
}
public void sayHello()
{
System.out.println("hi,world");
}
}
接着我们来看HelloAgent.java吧
/*
* Created on 2005-3-17
* @Author roson
*
*/
package bean;
import com.sun.jdmk.comm.*;
import java.lang.management.*;
import javax.management.*;
public class HelloAgent {
public static void main(String[] args) {
MBeanServer server=ManagementFactory.getPlatformMBeanServer();
HtmlAdaptorServer adaptor=new HtmlAdaptorServer();
HelloMBean hello1=new Hello();
HelloMBean hello2=new Hello();
try
{
ObjectName helloObjectName1=new ObjectName("bean:type=Hello,name=hello1");
server.registerMBean(hello1,helloObjectName1);
ObjectName helloObjectName2=new ObjectName("bean:type=Hello,name=hello2");
server.registerMBean(hello2,helloObjectName2);
ObjectName adaptorObjectName=new ObjectName("HelloServer:type=htmlAdaptor,port=8082");
adaptor.setPort(8082);
server.registerMBean(adaptor,adaptorObjectName);
adaptor.start();
System.out.println("waiting . . .");
Thread.sleep(Long.MAX_VALUE);
}
catch(InterruptedException e)
{
System.out.println("Sleep stoped");
e.printStackTrace();
}
catch(MalformedObjectNameException e)
{
System.out.println("bad objectName");
e.printStackTrace();
}
catch(InstanceAlreadyExistsException e)
{
System.out.println("already exits");
}
catch(MBeanRegistrationException e)
{
System.out.println("registeration error");
}
catch(NotCompliantMBeanException e)
{
System.out.println("registeration error");
}
}
}
改动的地方我已经用红颜色区分开了,大家如果属性的话就可以参考和以前的区别咯。我在这里也加了HtmlAdaptorServer。
运行:
1、 编译(这个不用说了吧,当然有些包是要加进去的咯)
2、 java -Dcom.sun.management.jmxremote HelloAgent
3、 运行jconsole( 在jdk 1.5.0 _02/bin/jconsole.exe)
4、 跳出对话框,如有PID的话就可以连接了。接下来大家就自己熟悉下这个工具咯。
参考:http://java.sun.com/j2se/1.5.0/docs/guide/jmx/tutorial/essential.html#wp1053244