Two message models for JMS (point-to-point-to-peer and Publish/subscribe (pub/sub)) Examples of applications

Source: Internet
Author: User
Tags commit gettext message queue jboss
It programmer development Essentials-all kinds of resources download list, history of the most IT resources, personal collection summary.


1. Peer model
The following concepts are found in the peer-to model: Message Queuing (queue), Sender (sender), receiver (receiver). Each message is sent to a specific queue, and the recipient obtains the message from the queue. The queue retains messages until they are consumed or timed out.
 Only one consumer per message (Consumer) (i.e., once consumed, the message is no longer in the message queue)
 There is no dependency on time between the sender and the receiver, that is, when the sender sends the message, regardless of whether the receiver is running, it does not affect the message being sent to the queue.
 The recipient must answer the queue successfully after receiving the message successfully
If every message you want to send should be handled successfully, then you need a peer model.
Example:
Registers the message listener, calls the OnMessage method when a message is sent (implements the MessageListener interface)
Java code   import javax.ejb.activationconfigproperty;   import javax.ejb.messagedriven;    import javax.jms.jmsexception;   import javax.jms.message;   Import  javax.jms.MessageListener;   import javax.jms.textmessage;      @ Messagedriven (activationconfig={                 @ActivationConfigProperty (propertyname= "destinationtype", propertyvalue= "Javax.jms.Queue"),                @ActivationConfigProperty (PropertyName = "Destination",  propertyvalue= "Queue/myqueue")        }  )     public class queuemessagebean implements messagelistener {           public void onmessage (message msg)  {            //has the following message types            //1 text            //2 Map            //3 Object           //4  stream           //5 byte            TextMessage txtMsg =  (textmessage) msg;            String s =  "";            try {                s = txtmsg.gettext ();           } catch   (jmsexception e)  {                e.printstAcktrace ();           }            system.out.println ("Queuemessagebean received the message:"  + s);        }  }  //client calls    import javax.jms.message;   Import  javax.jms.MessageProducer;   import javax.jms.queue;   import  javax.jms.queueconnection;   import javax.jms.queueconnectionfactory;   import  javax.jms.queuesession;   import javax.naming.initialcontext;          public class test {       public static void  Main (String[] args)  throws Exception {       initialcontext  ctx = new initialcontext ();       // Get Queueconnectionfactory Objects        queueconnectionfactory factory =  (queueconnectionfactory)  ctx.lookup (" Queueconnectionfactory ");       //create queueconnection          queueconnection connection = factory.createqueueconnection ();       //Create session        //ARG1: Related to a thing, true means last commit, false means auto-commit         //ARG2: Indicates that the message sends a confirmation notification to the middleware, where the type of automatic notification is used         queuesession session =  (queuesession)  connection.createqueuesession (false,  Queuesession.auto_acknowledge);       //get destination        Queue queue =  (Queue)  ctx.lookup ("Queue/myqueue");        //News producers        MessageProducer sender =  Session.createproducer (queue);       //definition message        message msg = session.createtextmessage ("The message came ");       //Send Message        sender.send (queue, msg);        session.close ();       connection.close ();                   }  }   

2. Pub/sub mode
In the PUB/SUB model, there are the following concepts: Subject (Topic), publisher (publisher), Subscriber (subscriber). The client sends the message to the topic. Multiple publishers send messages to topic, which the system passes to multiple subscribers.
 Each message can have multiple consumers
 There is a time dependency between the Publisher and the Subscriber. Subscribers to a topic (TOPIC) must create a subscription before they can consume the publisher's message and, in order to consume the message, the Subscriber must remain in a running state.
Of course, to mitigate this strict time dependency, JMS allows subscribers to create a durable subscription. This way, even if the Subscriber is not activated (running), it can receive the message from the publisher.
You can use the PUB/SUB model if you want to send messages that can be processed without being processed, handled by a consumer, or can be processed by multiple consumers.

Registers the message listener, calls the OnMessage method when a message is sent (implements the MessageListener interface)
Java code   import javax.ejb.activationconfigproperty;   import javax.ejb.messagedriven;    import javax.jms.jmsexception;   import javax.jms.message;   Import  javax.jms.MessageListener;   import javax.jms.textmessage;      @ Messagedriven (activationconfig={                 @ActivationConfigProperty (propertyname= "destinationtype", propertyvalue= "Javax.jms.Topic"),                @ActivationConfigProperty (PropertyName = "Destination",  propertyvalue= "Topic/mytopic")        }  )     public class topicmessagebean implements messagelistener {           public void onmessage (message msg)  {            //has the following message types            //1 text            //2 Map            //3 Object           //4  stream           //5 byte            TextMessage txtMsg =  (textmessage) msg;            String s =  "";            try {                s = txtmsg.gettext ();           } catch   (jmsexception e)  {                e.printstAcktrace ();           }            system.out.println ("Topicmessagebean received the message:"  + s);        }  }     //Client testing    import javax.jms.messageproducer;    import javax.jms.topic;   import javax.jms.topicconnection;   Import  javax.jms.TopicConnectionFactory;   import javax.jms.topicsession;   import  javax.naming.initialcontext;         public class test {       public static void main (String[] args)  throws Exception  {       initialcontext ctx = new initialcontext ();        //Get queueconnectionfactory objects         Topicconnectionfactory factory =  (topicconnectionfactory)  ctx.lookup ("Topicconnectionfactory");        //creating Queueconnection         topicconnection  connection = factory.createtopicconnection ();       //Create session         //ARG1: Related to things, true means last commit, false means auto-commit        //ARG2: Indicates that the message sends a confirmation notification to the middleware, which is based on the type of automatic notification        TopicSession session =  ( topicsession)  connection.createtopicsession (False, topicsession.auto_acknowledge);        //get destination       Topic queue =  (Topic)  ctx.lookup ("Topic/mytopic");       //message producer         messageproducer publisher = session.createproducer (queue);        //Defining Messages       message msg = session.createtextmessage ("message coming");        //Send Message        publisher.send (queue, msg);        session.close ();       connection.close ();                   }  }  

Two model implementations: there can only be one consumer for each message of the peer-to-peer model if we define a bean of two message receivers, then only a single end will receive the message. When you remove the message receiving bean deployed in JBoss and then send the message at this time the message is in the queue and once you redeploy he will immediately receive the message just sent so it has no time dependency, the PUB/SUB model can have multiple consumers In this model, if we define multiple beans that receive messages when we send a message to the client, two beans will receive the message, so he has multiple consumers but if you remove the message receiving bean from the JBoss deployment, send the message. Then after redeployment, the message is not received, so he has a time dependency.

Understanding of several concepts in the code
Connection Factory
The factory that created the connection object has two queueconnectionfactory and topicconnectionfactory for two different JMS message models. You can find the ConnectionFactory object through Jndi.

Destination
Destination means that the message producer's message is sent to the target or to the source of the message consumer. For a message producer, its destination is a queue or a topic (Topic), and for the message consumer, its destination is also a queue or topic (that is, the source of the message).

So, destination is actually two kinds of objects: Queue, Topic.

You can find destination through Jndi.

Connection:
Connection represents the link established between the client and the JMS system (the wrapper to the TCP/IP socket). Connection can produce one or more sessions. Like ConnectionFactory, there are two types of connection: Queueconnection and Topicconnection.
Session:
The session is the interface where we manipulate the message. You can create producers, consumers, messages, etc. through the session. The session provides the functionality of the transaction. These send/Receive actions can be placed in a transaction when we need to send/receive multiple messages using the session. Similarly, queuesession and topicsession are also divided.
Message producers:
The message producer is created by the session and is used to send messages to destination. Similarly, there are two types of message producers: Queuesender and Topicpublisher. You can call the message producer's method (send or Publish method) to send the message.
Message consumers:
The message consumer is created by the session to receive messages sent to destination. Two types: QueueReceiver and TopicSubscriber. Can be created by Createreceiver (Queue) or Createsubscriber (Topic) of the session, respectively. Of course, you can also create a persistent subscriber by using the Createdurablesubscriber method of the session.
MessageListener:
Message listeners. If a message listener is registered, the listener's OnMessage method is automatically invoked once the message arrives. An MDB (Message-driven Bean) in an EJB is a messagelistener.

MDB Introduction:
For the client, the Message-driven Bean is the consumer of the asynchronous message. When the message arrives, the container is responsible for invoking the MDB. The client sends a message to Destination,mdb as a messagelistener to receive the message.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.