这里简单用jmx实现下agent对mbean的管理,以及notification的使用。
5个主要类:
SystemTimeAgent: 对资源进行管理的agent。它通过接入HtmlAdaptorServer,把管理的资源和管理方法通过http方式暴露给浏览器。我们可以通过浏览器来浏览资源属性和操作资源,甚至触发资源发送消息。
SystemTimeMBean: SystemTime的MBean接口
SystemTime: MBean实现。同时是消息接受者,它可以通过handleNotification对消息进行相应。
SystemLoadMBean: SystemLoad的MBean接口
SystemLoad: MBean实现. 同时是消息发送者,它可以通过emitTime()方法发送notification,相应订阅者可以接受到消息并相应
SystemTimeMBean
public interface SystemTimeMBean {
Date getSystemTime();
void setSystemTime(Date date);
void printSystemTime();
}
SystemLoadMBean
public interface SystemLoadMBean {
int getLoad();
void setLoad(int load);
void emitTime();
}
agent:
public class SystemTimeAgent {
private MBeanServer mbs = null;
SystemTimeAgent() {
mbs = MBeanServerFactory.createMBeanServer("SystemTime");
HtmlAdaptorServer adapter = new HtmlAdaptorServer();
SystemTime st = new SystemTime();
SystemLoad load = new SystemLoad();
ObjectName stName = null;
ObjectName loadName = null;
ObjectName adapterName = null;
try {
stName = new ObjectName( "SystemTime:name=st1" );
mbs.registerMBean( st, stName );
adapterName = new ObjectName( "SystemTime:name=htmladapter,port=9092" );
adapter.setPort(9092);
mbs.registerMBean(adapter, adapterName);
adapter.start();
loadName = new ObjectName("SystemLoad:name1=load");
mbs.registerMBean(load, loadName);
mbs.addNotificationListener(loadName, st, null, null);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main( String args[] )
{
System.out.println( "SystemTimeAgent is running" );
SystemTimeAgent agent = new SystemTimeAgent();
}
}
订阅者:SystemTime:
public class SystemTime implements SystemTimeMBean, NotificationListener {
private Date time;
public SystemTime() {
time = new Date();
}
public SystemTime(String dateString) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
time = sdf.parse(dateString);
} catch (ParseException e) {
e.printStackTrace();
}
}
@Override
public Date getSystemTime() {
return time;
}
@Override
public void setSystemTime(Date date) {
this.time = date;
}
@Override
public void printSystemTime() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(sdf.format(time));
}
@Override
public void handleNotification(Notification notification, Object handback) {
if ("SystemLoad.notification" .equals(notification.getType())) {
printSystemTime();
}
}
}
消息发布者:SystemLoad
public class SystemLoad extends NotificationBroadcasterSupport implements SystemLoadMBean {
private int load;
@Override
public int getLoad() {
return load;
}
@Override
public void setLoad(int load) {
this.load = load;
}
public SystemLoad() {
load = (int)(100*Math.random());
}
@Override
public void emitTime(){
Notification notif = new Notification("SystemLoad.notification", this, -1, "load:"+load);
sendNotification(notif);
}
}