Writing a Consumer class

Let's now write the Consumer class to receive the message from the queue. On the Consumer side, we still need the JMSContext to retrieve the messages from the queue. The code looks similar to that which we wrote for the producer:

class Consumer {
@Inject
private lateinit var initialContext: InitialContext

fun receiveMessage(): String {
val queue = initialContext.lookup("jms/PointToPointQueue") as Queue
val connectionFactory = initialContext.lookup("jms/__defaultConnectionFactory") as
ConnectionFactory
val message = connectionFactory
.createContext()
.createConsumer(queue)
.receiveBody(String::class.java)

println("Message received $message")
return message
}
}

We looked up the queue using a JNDI lookup and we loaded the defaultConnectionFactory. Then, we created JMSContext using the createContext() function invoked on connectionFactory. We created the consumer, passed the queue that we looked up, and invoked the receiveBody() function to retrieve the message sent by the producer.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset