1.How to do lookup in JMS.
What is the difference between topic and queue?
A topic is typically used for one to many messaging i.e. it supports publish subscribe model of messaging.
While queue is used for one-to-one messaging i.e. it supports Point to Point Messaging.
2.JMS step by step.
Queue
Topic
Connection
define JNDI name for queue
JMS API Architecture
A JMS application is composed of the following parts.
Pub/sub messaging has the following characteristics.
- Each message can have multiple consumers.
- Publishers and subscribers have a timing dependency. A client that subscribes to a topic can consume only messages published after the client has created a subscription, and the subscriber must continue to be active in order for it to consume messages.
/*
* Look up connection factory and queue. If either does
* not exist, exit.
*/
try {
queueConnectionFactory = (QueueConnectionFactory)
jndiContext.lookup("java:comp/env/jms/MyQueueConnectionFactory");
queue = (Queue)
jndiContext.lookup("java:comp/env/jms/QueueName");
} catch (NamingException e) {
System.out.println("JNDI lookup failed: " +
e.toString());
System.exit(1);
}
/*
* Create connection.
* Create session from connection; false means session is
* not transacted.
* Create sender and text message.
* Send messages, varying text slightly.
* Finally, close connection.
*/
try {
queueConnection =
queueConnectionFactory.createQueueConnection();
queueSession =
queueConnection.createQueueSession(false,
Session.AUTO_ACKNOWLEDGE);
queueSender = queueSession.createSender(queue);
message = queueSession.createTextMessage();
for (int i = 0; i < NUM_MSGS; i++) { message.setText("This is message " + (i + 1)); System.out.println("Sending message: " + message.getText()); queueSender.send(message); }
Receiving Message Using MDB
---------------------------
- public interface TextMessage extends Message
ATextMessageobject is used to send a message containing ajava.lang.String. It inherits from theMessageinterface and adds a text message body. implement the Message Driven Bean with implements MessageDrivenBean, MessageListener /** * onMessage method, declared as public (but not final or * static), with a return type of void, and with one argument * of type javax.jms.Message. * * Casts the incoming Message to a TextMessage and displays * the text. * * @param inMessage the incoming message */ public void onMessage(Message inMessage) { TextMessage msg = null; try { if (inMessage instanceof TextMessage) { msg = (TextMessage) inMessage; System.out.println("MESSAGE BEAN: Message " + "received: " + msg.getText()); } else { System.out.println("Message of wrong type: " + inMessage.getClass().getName()); } } catch (JMSException e) { System.err.println("MessageBean.onMessage: " + "JMSException: " + e.toString()); mdc.setRollbackOnly(); } catch (Throwable te) { System.err.println("MessageBean.onMessage: " + "Exception: " + te.toString()); } } } catch (JMSException e) {
0 Comments:
Post a Comment