Create a Message Listener for Asynchronous Message Consumption
EMS allows a Message Consumer to consume messages either synchronously or asynchronously. For synchronous consumption, the Message Consumer explicitly calls a receive method on the topic or queue. For asynchronous consumption, you can implement a Message Listener that serves as an asynchronous event handler for messages.
A Message Listener implementation has one method, onMessage, that is called by the EMS server when a message arrives on a destination. You implement the onMessage method to perform the desired actions when a message arrives. Your implementation should handle all exceptions, and it should not throw any exceptions.
Once you create a Message Listener, you must register it with a specific Message Consumer before calling the connection’s start method to begin receiving messages.
A Message Listener is not specific to the type of the destination. The same listener can obtain messages from a queue or a topic, depending upon the destination set for the Message Consumer with which the listener is registered.
- Java
public class tibjmsAsyncMsgConsumer implements MessageListener { /* Create a connection, session and consumer */ ... MessageConsumer QueueReceiver = session.createConsumer(queue); QueueReceiver.setMessageListener(this); connection.start(); }
public void onMessage(Message message) { /* Process message and handle exceptions */ }
See the tibjmsAsyncMsgConsumer.java sample client for a working example.
- C
void onMessage(tibemsMsgConsumer QueueReceiver, tibemsMsg message, void* closure) { /* Process message and handle exceptions */ }
In another function, that creates a tibemsMsgConsumer and uses the tibemsMsgConsumer_SetMsgListener function to create a message listener for the Message Consumer, specifying onMessage() as the callback function:
void run() { tibemsMsgConsumer QueueReceiver = NULL; /* Create a connection, session and consumer */ ... status = tibemsSession_CreateConsumer(session, &QueueReceiver, queue, NULL, TIBEMS_FALSE); status = tibemsMsgConsumer_SetMsgListener(QueueReceiver, onMessage, NULL); status = tibemsConnection_Start(connection); }
See the tibemsAsyncMsgConsumer.c sample client for a working example.
- C#
public class csAsyncMsgConsumer : IMessageListener { /* Create a connection, session and consumer */ ... MessageConsumer QueueReceiver = session.CreateConsumer(queue); QueueReceiver.MessageListener = this; connection.Start(); }
public void OnMessage(Message message) { try { /* Process message and handle exceptions */ } }
See the csAsyncMsgConsumer.cs and csAsyncMsgConsumerUsingDelegate.cs sample clients for working examples.