连接事件通知允许 Message Queue 客户端侦听关闭和重新连接事件,并根据通知类型和连接状态采取适当的操作。例如,如果发生故障转移,并且客户端重新连接到了其他代理,则应用程序可能希望清除事务状态,并继续执行新事务。
如果 Message Queue 提供程序检测到某个连接存在严重问题,它将调用该连接对象的已注册的异常侦听器。它调用侦听器的 onException 方法,并向其传递一个用于描述该问题的 JMSException 参数。Message Queue 提供程序还提供一个事件通知 API,该 API 允许客户端运行时环境向应用程序通知有关连接状态更改的信息。通知 API 由以下元素定义:
com.sun.messaging.jms.notification 软件包,用于定义事件侦听器和通知事件对象。
com.sun.messaging.jms.Connection 接口,用于定义 javax.jms.Connection 接口的扩展。
以下部分介绍了可以触发通知的事件,并说明了如何创建事件侦听器。
下表列出并介绍了事件侦听器可以返回的事件。
请注意,当发生连接事件时,不会调用 JMS 异常侦听器。仅当客户端运行时环境达到最大重新连接尝试次数时,才会调用异常侦听器。客户端运行时环境在调用异常侦听器之前,始终会调用事件侦听器。
表 1–8 通知事件
事件类型 |
含义 |
---|---|
ConnectionClosingEvent |
如果 Message Queue 客户端运行时环境从代理收到通知,指明由于管理员请求关闭而即将关闭连接,则 Message Queue 客户端运行时环境将生成此事件。 |
ConnectionClosedEvent |
关闭连接时(由于代理错误或管理员请求关闭或重新启动连接),Message Queue 客户端运行时环境将生成此事件。 如果事件侦听器收到 ConnectionClosedEvent,则应用程序可以使用所收到的事件的 getEventCode() 方法,来获取用于指明关闭原因的事件代码。 |
ConnectionReconnectedEvent |
Message Queue 客户端运行时环境已重新连接到代理。此代理可以是客户端先前连接的代理,也可以是其他代理。 应用程序可以使用所收到的事件的 getBrokerAddress 方法,来获取它所重新连接到的代理的地址。 |
ConnectionReconnectFailedEvent |
Message Queue 客户端运行时环境无法重新连接到代理。每次重新连接尝试失败时,该运行时环境都会生成新的事件,并将该事件传送到事件侦听器。 发生连接事件时不会调用 JMS 异常侦听器。仅当客户端运行时环境达到最大重新连接尝试次数时,才会调用 JMS 异常侦听器。客户端运行时环境在调用异常侦听器之前,始终会调用事件侦听器。 |
以下代码示例说明了如何设置连接事件侦听器。只要发生连接事件,客户端运行时环境就会调用事件侦听器的 onEvent 方法。
//create an MQ connection factory. com.sun.messaging.ConnectionFactory factory = new com.sun.messaging.ConnectionFactory(); //create an MQ connection. com.sun.messaging.jms.Connection connection = (com.sun.messaging.jms.Connection )factory.createConnection(); //construct an MQ event listener. The listener implements //com.sun.messaging.jms.notification.EventListener interface. com.sun.messaging.jms.notification.EventListener eListener = new ApplicationEventListener(); //set event listener to the MQ connection. connection.setEventListener ( eListener );
在此示例中,应用程序选择让事件侦听器将连接事件记录到应用程序的日志记录系统中:
public class ApplicationEventListener implements com.sun.messaging.jms.notification.EventListener { public void onEvent ( com.sun.messaging.jms.notification.Event connEvent ) { log (connEvent); } private void log ( com.sun.messaging.jms.notification.Event connEvent ) { String eventCode = connEvent.getEventCode(); String eventMessage = connEvent.getEventMessage(); //write event information to the output stream. } }