还可使用非消息驱动的 bean 创建事件使用者。
// Get notification helper factory from JNDI InitialContext context = new InitialContext(); Object notificationHelperFactoryObject = context.lookup("com/ibm/events/NotificationHelperFactory"); NotificationHelperFactory nhFactory = (NotificationHelperFactory) PortableRemoteObject.narrow(notificationHelperFactoryObject, NotificationHelperFactory.class); // Create notification helper NotificationHelper notificationHelper = nhFactory.getNotificationHelper();
notificationHelper.setEventSelector("CommonBaseEvent[@severity > 30]");
每个事件组可以与一个 JMS 主题和任意数目的 JMS 队列相关联。您可以查询通知辅助控件来确定哪些目标与特定事件组相关联。
要查找与事件组关联的主题,使用 NotificationHelper 的 getJmsTopic(String) 方法并指定事件组的名称:MessagePort msgPort = notificationHelper.getJmsTopic("critical_events");要找到与某个事件组相关联的队列,请使用 getJmsQueues(String) 方法:
MessagePort[] msgPorts = notificationHelper.getJmsQueues("critical_events");返回的对象是一个表示 JMS 主题的 MessagePort 对象或一组表示 JMS 队列的 MessagePort 对象。MessagePort 实例是包含目标及其连接工厂的 JNDI 名称的包装程序对象。
String connectionFactoryName = msgPort.getConnectionFactoryJndiName(); String destinationName = msgPort.getDestinationJndiName(); // create connection and session ConnectionFactory connectionFactory = (ConnectionFactory) context.lookup(connectionFactoryName); Connection connection = connectionFactory.createConnection(); Session session = connection.createSesion(false, Session.CLIENT_ACKNOWLEDGE); // Create consumer and register listener Topic topic = (Topic) context.lookup(destinationName); MessageConsumer consumer = session.createConsumer(topic); consumer.setMessageListener(this); connection.start();
在侦听器的 onMessage() 方法中,使用通知辅助控件将接收到的每个 JMS 消息转换为包含事件通知的数组。(如果该事件与通知辅助控件中指定的事件选择器不匹配,则该数组是空的。)事件通知是实现 EventNotification 接口的类的实例。
public void onMessage(Message msg) { EventNotification[] notifications = notificationHelper.getEventNotifications(msg); // ...
通知类型 | 描述 |
---|---|
CREATE_EVENT _NOTIFICATION_TYPE |
已在与目标相关联的事件组中创建了新事件。这表示新事件已发送或者现有事件已更改,所以它现在与事件组定义相匹配。该通知还包含完整事件数据。 |
REMOVE_EVENT _NOTIFICATION_TYPE |
存储在事件数据库中并且已从与目标相关联的事件组中除去的事件。这表示新事件已从事件数据库中删除或者现有事件已更改,所以它不再与事件组定义相匹配。通知还包含已删除事件的全局实例标识。 |
UPDATE_EVENT _NOTIFICATION_TYPE |
已经按某种方式对存储在事件数据库中的事件进行了更新,这种更新方式不会改变它在与目标相关联的事件组中的成员资格。该通知还包含完整事件数据。 |
for (int i = 0; i < notifications.length; i++) { int notifType = notifications[i].getNotificationType(); if(notifType == NotificationHelper.CREATE_EVENT_NOTIFICATION_TYPE) { CommonBaseEvent event = notifications[i].getEvent(); if (event != null) { // process the new event // ... } } else if(notifType == NotificationHelper.UPDATE_EVENT_NOTIFICATION_TYPE) { CommonBaseEvent event = notifications[i].getEvent(); if (event != null) { // process the updated event // ... } } else if(notifType == NotificationHelper.REMOVE_EVENT_NOTIFICATION_TYPE) { String eventId = notifications.[i].getGlobalInstanceId(); // process the event deletion // ... } }