How it works...

We start by asking the application server a JMS context instance:

@Inject
private JMSContext context;

We also send a reference to the queue we want to work with:

@Resource(lookup = "jms/JmsQueue")
private Destination queue;

Then, using the context, we create a producer to send the message to the queue:

context.createProducer()
.setDeliveryMode(DeliveryMode.PERSISTENT)
.setDisableMessageID(true)
.setDisableMessageTimestamp(true)
.send(queue, user);

Pay attention to these three methods:

  • setDeliveryMode: This method can be PERSISTENT or NON_PERSISTENT. If using PERSISTENT, the server will take special care of the message and not lose it.
  • setDisableMessageID: This one is used for creating MessageID, which increases the server effort to create and deliver the message and also increases its size. This property (true or false) gives a hint to the server that you are not going to need/use it, so it can improve the process.
  • setDisableMessageTimestamp: This is the same as for setDisableMessageID.

Also, note that we are sending a User instance to the queue. So you can easily send object instances, not only text messages, as long as they implement the serializable interface.

The MDB itself, or our message consumer, is basically a few annotations and an interface implementation.

Here is its annotation:

@MessageDriven(activationConfig = {
@ActivationConfigProperty(propertyName = "destinationLookup",
propertyValue = "jms/JmsQueue"),
@ActivationConfigProperty(propertyName = "destinationType",
propertyValue = "javax.jms.Queue")
})

Here, we are using two properties: one to define which queue we are looking up (destinationLookup) and another to define that it is really the queue type we are using (destinationType).

Here is the implementation:

@Override
public void onMessage(Message msg) {
try {
User user = msg.getBody(User.class);
System.out.println("User: " + user);
} catch (JMSException ex) {
System.err.println(ex.getMessage());
}
}

Note that it is easy to get the User instance from the message's body:

User user = msg.getBody(User.class);

No heavy lifting at all.

And the endpoint used to send the message couldn't be simpler. We inject the Sender (which is a stateless bean):

@Inject
private Sender sender;

Then, we call an asynchronous method:

public void mdbService(@Suspended AsyncResponse response){
long id = new Date().getTime();
sender.send(new User(id, "User " + id));
response.resume("Message sent to the queue");
}
..................Content has been hidden....................

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