Writing a producer class

After creating the Maven project with these dependencies, we will create a message Producer class:

class Producer{
}

We need to initialize InitialContext here. InitialContext bootstraps the context and provides the entry point for the resolution of the named resources that we created in the GlassFish server.

We will inject InitialContext through Context Dependency Injection (CDI) as follows:

class Producer {
@Inject
private lateinit var initialContext: InitialContext
}

As we said earlier, queues are used in the point-to-point messaging model. We look for a queue using a JNDI lookup and this will return a reference object to a queue. This queue will be used to send messages by the producer and to read messages by the consumer.

We also need to look up the ConnectionFactory using JNDI. We use this connectionFactory to create the JMSContext, using which we can send messages to the queue:

val queue = initialContext.lookup("jms/PointToPointQueue") as Queue
val connectionFactory = initialContext.lookup("jms/__defaultConnectionFactory") as ConnectionFactory

We will create a producer using JMSContext. The createContext() function returns an instance of JMSContext. This is shown in the following code:

 connectionFactory.createContext()
.createProducer()
.send(queue, message)

Our Producer class looks as follows:

class Producer {
@Inject
private lateinit var initialContext: InitialContext

fun sendMessage(message: String): String {
try {
val queue = initialContext.lookup("jms/PointToPointQueue") as Queue
val connectionFactory = initialContext.lookup("jms/__defaultConnectionFactory") as
ConnectionFactory
connectionFactory.createContext()
.createProducer()
.send(queue, message)
println("Message sent")
return "Message sent"
}catch ( e: NamingException){
println("unable to load a resource "+e.message)
return "Unable to deliver a message"
}
}
}

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

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