ActiveMQ中advisory的使用和原理
在ActiveMQ中的监控和管理也可以通过Advisory实现对消息生产者和消息消费者以及队列的监控。Advisory实质通过事件监听实现。
调用过程的序列图如下:

1.在Advisory中实现对队列目标的监控:
A.队列目标的事件类:DestinationEvent继承EventObject实现对DestinationInfo的监控。
B.通过队列目标的监听实现对队列事件的监控
public interface DestinationListener {
void onDestinationEvent(DestinationEvent event);
}
C.通过DestinationSource类实现对Broker中队列目标Destination的跟踪。
2.在Advisory中实现对消费者的监控:
A.通过抽象类ConsumerEvent实现对消费者的监控。ConsumerEvent继承自EventObject。
针对对Consumer监控和管理由子类ConsumerStartedEvent和ConsumerStoppedEvent实现。
B.通过消费者监听实现对消费者的监听。
public interface ConsumerListener {
void onConsumerEvent(ConsumerEvent event);
}
C.通过ConsumerEventSource对消费者的监听。
3.在Advisory中实现对生产者的监控:
A.通过抽象类ProducerEvent实现对消费者的监控。ProducerEvent继承自EventObject。
针对对Producter监控和管理由子类ProducerStartedEvent和ProducerStoppedEvent实现。
B.通过生产者监听实现对消费者的监听。
public interface ProducerListener {
void onProducerEvent(ProducerEvent event);
}
C.通过ProducerEventSource对消费者的监听。
自定义事件:
package easyway.app.activemq.demo.events;
import java.util.EventObject;
/**
* 通过EasywayEvent.java文件创建EasywayEvent类,这个类继承EventObject。这个类的构造函数的参数传递了产生这个事件的事件源(比如各种控件),方法getSource用来获得这个事件源的引用。
* @author Owner
*
*/
public class EasywayEvent extends EventObject
{
/**
*
*/
private static final long serialVersionUID = 1L;
Object obj;
public EasywayEvent(Object source)
{
super(source);
obj = source;
}
public Object getSource()
{
return obj;
}
public void say()
{
System.out.println("This is say method...");
}
}
监听器:
package easyway.app.activemq.demo.events;
/**
* 定义新的事件监听接口,该接口继承自EventListener;该接口包含对DemeEvent事件的处理程序:
*/
import java.util.EventListener;
public interface EasywayListener extends EventListener
{
public void easywayEvent(EasywayEvent dm);
}
事件监听实现类:
package easyway.app.activemq.demo.events;
public class EasyWayListener1 implements EasywayListener
{
public void easywayEvent(EasywayEvent dm) {
System.out.println("Inside listener1...");
}
}
测试类:
package easyway.app.activemq.demo.events;
import java.util.*;
/**
* 通过EasyWaySource..ava文件创造一个事件源类,它用一个java.utile.Vector对象来存储所有的事件监听
* 器对象,存储方式是通过addListener(..)这样的方法。notifyDemeEvent(..)是触发事件的方法,
* 用来通知系统:事件发生了,你调用相应的处理函数(回调函数)吧。
* @author Owner
*
*/
public class EasyWaySource {
private Vector<EasywayListener> repository = new Vector<EasywayListener>();
EasywayListener dl;
public EasyWaySource()
{
}
public void addDemoListener(EasywayListener dl)
{
repository.addElement(dl);
}
public void notifyDemoEvent()
{
Enumeration enum1 = repository.elements();
while(enum1.hasMoreElements())
{
dl = (EasywayListener)enum1.nextElement();
dl.easywayEvent(new EasywayEvent(this));
}
}
}