ActiveMQ Getting Started Series 3: publish / subscribe model

"In the last one : Getting Started with code examples (point to point) ActiveMQ Getting Started Series II referred to" in the two modes of ActiveMQ: point to point (PTP) and publish / subscribe model (Pub & Sub), introduces the ad hoc mode and use code examples will be described, today publish / subscribe model on the next introduction.

First, the theoretical basis

Publish / subscribe model diagram of work:

  • Message producers message (publish) to the topic, you can have multiple messages at the same time consumers (subscription) consume the message.
  • And point to point in different ways, a message posted to the topic will be consumed by all subscribers.
  • When the producers announced that regardless of whether consumers will not save the message.
  • Consumers must first message, after the producer of the message.

Second, code implementation

  1. Producers
    package com.sam.topic;
    
    import org.apache.activemq.ActiveMQConnectionFactory;
    
    import javax.jms.*;
    
    /**
     * @author JAVA开发老菜鸟
     *
     */
    public class TopicProducer {
    
        public static final  String QUEUE_NAME = "topic-demo";//队列名
    
        public void producer(String message) throws JMSException {
            ConnectionFactory factory = null;
            Connection connection = null;
            Session session = null ; 
            the MessageProducer Producer = null ;
             the try {
                 / ** 
                 * Create Connection Factory 1. 
                 * Creating the plant, the constructor has three parameters: namely, user name, password, the connection address 
                 * constructor with no arguments: has a default connection address, localhost 
                 * one parameter: no authentication mode, no user authentication 
                 * three parameters: an authentication and connection address 
                 * / 
                Factory = new new ActiveMQConnectionFactory ( "ADMIN", "ADMIN", "TCP: // localhost: 61616" );
                 / ** 
                 * 2. create connection 
                 * no parameters 
                 * there are parameters: user name, password 
                 * / 
                connection = factory.createConnection ();
                / ** 
                 * 3. Start connection 
                 * Producers can not start because the back check when sending messages 
                 * If you did not initiate the connection will automatically start 
                 * If you have a special configuration needs to be configured to start after the completion of the connection 
                 * / 
                Connection. Start (); 
                / ** 
                 * 4. create a connection session 
                 * there are two parameters: the need for services, message acknowledgment. 
                 * If support services for producers, the second parameter is invalid, the proposed incoming session. SESSION_TRANSACTED 
                 * If you do not support transactions, the second argument must be passed and effective 
                 * 
                 * AUTO_ACKNOWLEDGE: automatic confirmation after automatic confirmation message handling (commercial exploitation is not recommended) 
                 * CLIENT_ACKNOWLEDGE: client manual confirmation, you must manually confirm consumer handling 
                 * DUPS_OK_ACKNOWLEDGE : there is a copy of the manual confirmation of the client, the message may be multiple treatments (not recommended) 
                 * / 
                the session = connection.createSession ( false, Session.AUTO_ACKNOWLEDGE);
                 / ** 
                 * Create 5. The destination (subject) with the session, the producers, the message 
                 * queue name is unique label queue 
                 * created when the producer may not specify a destination, the transmission time can be designated 
                 * / 
                the destination Where do you want = session.createTopic (queue_name); 
                producer = session.createProducer (Where do you want); 
                TextMessage textMessage = session.createTextMessage (message);
                 / ** 
                 * 6. the message sent by the producer to the destination 
                 * / 
                producer.send (textMessage); 
                System.out.println ( "message sent successfully" ); 
            } the catch (Exception EX) {
                throw ex;
            } finally {
                /**
                 * 7.释放资源
                 */
                if(producer != null){
                    producer.close();
                }
    
                if(session != null){
                    session.close();
                }
    
                if(connection != null){
                    connection.close();
                }
            }
        }
    
        public static void main(String[] args){
            TopicProducer producer = new TopicProducer();
            try{
                producer.producer("hello, activemq");
            } catch (Exception ex){
                ex.printStackTrace();
            }
        }
    }

    Publish / producer and code-point mode The main difference between the subscription model is the way to create Destination, ad-hoc mode is invoked session.createQueue (QUEUE_NAME), and publish / subscribe model is to call session.createTopic (QUEUE_NAME).

  2. consumer
    Package Penalty for com.sam.topic; 
    
    Import org.apache.activemq.ActiveMQConnectionFactory; 
    
    Import . the javax.jms * ;
     Import java.io.IOException; 
    
    / ** 
     * @author JAVA development of old rookie 
     * 
     * observer consumption - monitor consumption 
     * / 
    public  class TopicConsumer { 
    
        public  void Consumer () throws a JMSException, IOException { 
            the ConnectionFactory Factory = null ; 
            Connection Connection = null ; 
            the Session the session = null ;
            MessageConsumer consumer = null;
            try {
                factory = new ActiveMQConnectionFactory("admin","admin","tcp://localhost:61616");
                connection = factory.createConnection();
                /**
                 * 消费者必须启动连接,否则无法消费
                 */
                connection.start();
                session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
                Destination destination = session.createTopic(TopicProducer.QUEUE_NAME);
                consumer =session.createConsumer (Where do you want);
                 / ** 
                 * registered listener, changes in the message queue automatically triggers the listener to receive and process messages automatically 
                 * 
                 * listener Once registered, permanent, until the program is closed 
                 * listener may register a plurality, corresponding to clusters 
                 * activemq automatically polls a plurality of listeners, parallel processing 
                 * / 
                consumer.setMessageListener ( new new the MessageListener () { 
                    @Override 
                    public  void the onMessage (the Message Message) { 
    
                        the try { 
                            TextMessage OM = (TextMessage) Message; 
                            Data String = om.getText (); 
                            System.out.println (Data); 
                        } the catch (a JMSException E) {
                            e.printStackTrace();
                        }
                    }
                });
            } catch(Exception ex){
                throw ex;
            }
        }
    
        public static void main(String[] args){
            TopicConsumer consumer = new TopicConsumer();
            try{
                consumer.consumer();
            } catch (Exception ex){
                ex.printStackTrace();
            }
        }
    }

    Consumers listening point to point on the basis of consumption changes, there are two main differences: 1. As with the producers, but also to create a different way of Destination; 2. the need to manually confirm the message, direct automatic confirmation mechanism

 

Code is finished, the next test due subscribe can have multiple, and each can consume the same message, so we started two consumers.

First execution Producer

I define the topic appeared in the Topics page of the console and there is a message sent successfully and not consumption

 

And then perform two consumers, two consumers do not consume any messages

In addition, the console page just more than two consumers have consumed the news or 0

 

 why? Remember the previous theoretical basis to say it? This is the reason

Continue our good start under the premise of two consumers, producers and then executed, this time will find two consumers consume the message

Look under the console page

It has consumed the message here is 2, issued before 2 this does not mean that the two messages are consumed, but that the second message is consumed twice, 1 * 2 = 2

Do not believe it, you can then execute again producer, this time is 4, not 3

3 had accumulated transmission message, the message consumer four times, two back 4 is consumed here are 2, 2 2 = 4 *

 

Third, the two models compare

 

Well, here, publish / subscribe model to introduce finished.

If you harvest, you point a praise chant

Guess you like

Origin www.cnblogs.com/sam-uncle/p/10990324.html