Enterprise Java Development@TOPIC@

Chapter 123. JMS API

123.1. JMS API Classes
123.2. ConnectionFactory
123.3. JMSContext
123.4. Destinations
123.4.1. JNDI Lookup
123.4.2. Injected Destination
123.5. Send Message
123.6. Receive Message
123.6.1. Poll from JMSConsumer
123.6.2. JMSConsumer Listener
123.6.3. Message Driven Bean (MDB)
123.7. Message Acknowledgement
123.7.1. Message Acknowledgement: AUTO_ACKNOWLEDGE
123.7.2. Message Acknowledgement: DUPS_OK_ACKNOWLEDGE
123.7.3. Message Acknowledgement: CLIENT_ACKNOWLEDGE
123.7.4. Message Acknowledgement: SESSION_TRANSACTED
123.8. JMS API Summary
  1. Obtain JMSContext from ConnectionFactory (JavaSE) or injection (JavaEE container)

  2. Obtain Destination from JNDI lookup (JavaSE) or injection (JavaEE container)

  3. Create Message

    import javax.jms.MapMessage;
    
    MapMessage message = jmsContext.createMapMessage();
    
  4. Set Message Properties (optional)

    import javax.jms.JMSException;
    
    message.setJMSType("saleUpdate"); //JMSType is a pre-defined property
    
    message.setStringProperty("awayClub", ...);//"awayClub" is example of user-defined String property
    message.setIntProperty("awayTeamId", ...); //"awayTeamId" is example of user-defined int property
  5. Set Message Payload

    //this example is a MapMessage - each Message type has specific interface
    
    message.setLong("id", item.getId());
    message.setString("name", item.getName());
    message.setString("seller", item.getOwner().getUserId());
    message.setLong("startDate", item.getStartDate().getTime());
    message.setLong("endDate", item.getEndDate().getTime());
    message.setDouble("minBid", item.getMinBid());
    message.setDouble("bids", item.getBids().size());
    message.setDouble("highestBid", 
            (item.getHighestBid() == null ? 0.00 : item.getHighestBid().getAmount()));            
  6. Create JMSProducer

    import javax.jms.Producer;
    
    JMSProducer producer = context.createProducer();
    
  7. Set JMSProducer options

    //JMSProducer supports method chaining
    
    producer.setPriority(Message.DEFAULT_PRIORITY)
            .setTimeToLive(Message.DEFAULT_TIME_TO_LIVE)
            .setDeliveryMode(Message.DEFAULT_DELIVERY_MODE)
            .setDeliveryDelay(Message.DEFAULT_DELIVERY_DELAY);
  8. Send Message to Destination

    producer.send(sellTopic, message);
    
  1. Obtain JMSContext from ConnectionFactory (JavaSE) or injection (JavaEE container)

  2. Obtain Destination from JNDI lookup (JavaSE) or injection (JavaEE container)

  3. Create a JMSConsumer for a specific destination

    import javax.jms.JMSConsumer;
    
    try (JMSConsumer syncConsumer = context.createConsumer(destination);
    
         JMSConsumer asyncConsumer = context2.createConsumer(destination)) {
    }
  4. Call receive() to obtain the next message

    Message message=consumer.receiveNoWait();
    
  5. Get Message Properties (optional)

    String level = message.getStringProperty("level");//"level" is user-defined property            
    
    logger.debug("receive ({}, mode={}, pri={}{}):{}",++count,
            message.getJMSDeliveryMode(),       //"JMSDeliveryMode" is pre-defined property
            message.getJMSPriority(),           //"JMSPriority" is pre-defined property
            (level==null?"":", level="+level),
            message.getJMSMessageID());         //"JMSMessageID" is pre-defined property
  6. Get Message Payload

    TextMessage m1 = ...
    
    TextMessage text = m1.request.getText();
    ObjectMessage m2 = ...
    XxxDTO dto = (XxxDTO)m2.getObject();
  7. Alternately, call JMS 2.0 receiveBody(T) to get just the payload

  1. Implement a javax.jms.MessageListener

    public class BuyerMDB implements MessageListener {
    
        public void onMessage(Message message) {
  2. Annotate the class as @MessageDriven

    
    
    @MessageDriven(activationConfig={
            @ActivationConfigProperty(
                    propertyName="destinationType",
                    propertyValue="javax.jms.Topic"),            
            @ActivationConfigProperty(
                    propertyName="destination",
                    propertyValue="java:/jms/topic/ejava/examples/asyncMarket/topic1"),            
            @ActivationConfigProperty(
                    propertyName="messageSelector",
                    propertyValue="JMSType in ('forSale', 'saleUpdate')"),
            @ActivationConfigProperty(
                    propertyName="acknowledgeMode",
                    propertyValue="Auto-acknowledge")            
    })
    public class BuyerMDB implements MessageListener {
        @PermitAll
        public void onMessage(Message message) {
  3. Grant container permission to invoke onMessage()

    
    
    @MessageDriven(...)
    public class BuyerMDB implements MessageListener {
        @PermitAll
        public void onMessage(Message message) {
  4. Process Messages as they are received through onMessage() callback