The Subscriber class is again similar to the Consumer class that we wrote earlier:
class Subscriber {
@Inject
private lateinit var initialContext: InitialContext
@Throws(NamingException::class)
fun listenToMessage(): String? {
val topic = initialContext.lookup("jms/Topic") as Topic
val connectionFactory = initialContext.lookup("jms/__defaultConnectionFactory")
as ConnectionFactory
var messageResponse = connectionFactory.createContext()
.createConsumer(topic)
.receiveBody(String::class.java)
return messageResponse
}
}
We load the topic and connectionFactory and we create JMSContext, using which we create a consumer by passing a topic to listen to. When the message is published by the publisher, this subscriber will receive the message.