We demonstrated the transactions in the point-to-point messaging model. The same can be enabled in the publish-subscribe model, as shown here:
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
val jmsContext = connectionFactory
.createContext(JMSContext.SESSION_TRANSACTED)
jmsContext.createProducer()
.send(topic, message)
jmsContext.commit()
}
}
The Subscriber model is as follows:
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
val jmsContext = connectionFactory
.createContext(JMSContext.SESSION_TRANSACTED)
var messageResponse = jmsContext.createConsumer(topic)
.receiveBody(String::class.java)
return messageResponse
}
}
The behavior is the same when we enable the transactions in the publish-subscribe model. Messages are not sent to the provider until the commit() function is invoked by the producer class and the message stays in the provider until commit() is called by the consumer class.