We write a Publisher class to publish a message to the topic:
class Publisher {
@Inject
private lateinit var initialContext: InitialContext
fun publishMessage(message: String) {
val topic = initialContext.lookup("jms/Topic") as Topic
val connectionFactory = initialContext.lookup("jms/__defaultConnectionFactory")
as ConnectionFactory
connectionFactory.createContext()
.createProducer()
.send(topic, message)
}
}
Again, this is similar to what we wrote in the Producer class.
We inject InitialContext using CDI, we look up the topic using JNDI, and we load connectionFactory. We then create JMSContext by invoking the createContext() function on the connectionFactory obtained. Using JMSContext, we create the producer instance and we invoke the send function by passing the message and the topic as the destination resource.