6.3. Creating and Closing Connections and Sessions with AMQP

6.3. Creating and Closing Connections and Sessions with AMQP

MRG Messaging can establish connections and sessions for use with Java JMS in two different ways. Many programs use JNDI to set up the initial session, then rely on the Java JMS APIs in their program code, as shown in the previous section. This is also the approach used in the examples in this chapter.

It is also possible to use the Qpid APIs to set up a session explicitly in your program, then use the Java APIs for programming with that session. The following skeleton shows how to do that:

Connection connection = new AMQConnection(broker_server, broker_port,
        broker_login, broker_password, "clientid/test", "");

connection.start();
Session session = connection.createSession(false,Session.AUTO_ACKNOWLEDGE);

// ---------- Your code goes here -------------------------

session.close();
connection.close();

For instance, the following code can be inserted into the above framework to create a queue, send a message, and read it back:

Destination destinationQueue = new AMQQueue("amq.direct","weather");
                                               
MessageProducer producerQueue = session.createProducer(destinationQueue);

TextMessage txtQueueMsg = session.createTextMessage();
txtQueueMsg.setText("Hello Queue");
                
producerQueue.send(txtQueueMsg);
                
MessageConsumer consumerQueue = session.createConsumer(destinationQueue);

Message msgQueue = consumerQueue.receive();
msgQueue.acknowledge();