Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.
Your application needs to receive messages from a JMS message broker.
The initial setup is similar to sending JMS messages: create a JNDI InitialContext object and look up the ConnectionFactory and destination from the JNDI context. Using the ConnectionFactory, create a Connection object and from the Connection, create a Session object. The Session object can be used to create a MessageConsumer for a destination. The MessageConsumer object has two methods for receiving messages, both named receive. If receive is called with no arguments, then the method blocks until a message is available. If receive is called with an argument (which must be numeric), the method blocks until a message is available or the specific number of milliseconds passes.
Example 4-3 contains some basic code for receiving a message. Once the message is received, it is inspected to see if it is a text message and, if so, the text is output.
Code View:
Scroll
/
Show All include Java
import java.util.Hashtable
import javax.naming.InitialContext
import javax.naming.Context
import javax.jms.Session
env = { Context::INITIAL_CONTEXT_FACTORY =>
"org.apache.activemq.jndi.ActiveMQInitialContextFactory",
Context::PROVIDER_URL =>
"tcp://localhost:61616" }
context = InitialContext.new(Hashtable.new(env))
connection_factory = context.lookup("ConnectionFactory")
destination = context.lookup("dynamicQueues/output.queue")
connection = connection_factory.create_connection()
session = connection.create_session(false, Session::AUTO_ACKNOWLEDGE)
consumer = session.create_consumer(destination)
connection.start
message = consumer.receive
if (message.respond_to? 'text')
p "message = #{message.text}"
else
p "message isn't a text message"
end
connection.stop
session.close
|
Note that in Example 4-3, we start the connection before receiving a message. A running connection is required before receiving messages whereas it is not for sending messages.