JMS Basics. Send and receive messages

Fast and easy way to send and receive JMS messages.

Albert Lacambra BasilAlbert Lacambra Basil

Send message

get a jms context
  @Inject
  @JMSConnectionFactory("java:/{ConnectionFactory}")
  JMSContext context;

if you want to hardcode credentials add the following annotation:

...
@JMSPasswordCredential(userName = "{user}", password = "{password}")
JMSContext context;
get a queue
  @Resource(lookup = "java:global/jms/{queueName}")
  Queue queue;
send a message
  context.createProducer().send(queue, message);

Receiving messages

Declare an async listener for incomming messages
@MessageDriven(name = "HelloWorldQueueMDB", activationConfig = {
    @ActivationConfigProperty(propertyName = "destinationLookup", propertyValue = "java:global/jms/{queueName}"),
    @ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue"),
    @ActivationConfigProperty(propertyName = "acknowledgeMode", propertyValue = "Auto-acknowledge")})
public class AsyncConsumer implements MessageListener {

  private static final Logger LOGGER = Logger.getLogger(AsyncConsumer.class.toString());

  public void onMessage(Message recivedMessage) {
    //Do something
  }
}

if you want to hardcode credentials add the following activationConfig:

@ActivationConfigProperty(propertyName = "user", propertyValue = "{user}"),
@ActivationConfigProperty(propertyName = "password", propertyValue = "{password}")
Authenticate on a MessageListener. Pass properties user and password.
@MessageDriven(activationConfig = {
    @ActivationConfigProperty(propertyName = "destinationLookup", propertyValue = "java:global/jms/pointsQueue"),
    @ActivationConfigProperty(propertyName = "connectionFactoryLookup", propertyValue = "java:jboss/exported/jms/RemoteConnectionFactory"),
    @ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue"),
    @ActivationConfigProperty(propertyName = "user", propertyValue = "jms"),
        @ActivationConfigProperty(propertyName = "password", propertyValue = "jms"),
        @ActivationConfigProperty(propertyName = "acknowledgeMode", propertyValue = "Auto-acknowledge")
})