消息中间件学习之JMS(3)

本篇主要介绍PUB/SUB模式

PUB/SUB模式区别于P2P模式,PUB/SUB模式下一个消息可以被多个消费者消息。消息生产者需要指定一个主题,即Topic。所有订阅该主题的消费者都能消费该生产者发送的消息。上代码:

session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

Topic topic = new ActiveMQTopic("LzyTopic");//此处创建一个主题

consumer1 = session.createConsumer(topic);//消费者1

consumer1.setMessageListener(new MessageListener() {

              @Override

                public void onMessage(Message arg0) {

                               TextMessage tm = (TextMessage) arg0;

                               if (tm != null) {

                                    try {

                                           System.out.println("consume1 and topic is"+ tm.getText());

                                    } catch (JMSException e) {

                                           e.printStackTrace();

                                    }

                                     }

                          }});///消费者1增加消息监听

consumer2 = session.createConsumer(topic);//消费者2

consumer2.setMessageListener(new MessageListener() {

           @Override

            public void onMessage(Message arg0) {

                      TextMessage tm = (TextMessage) arg0;

                      if (tm != null) {

                       try {

                                 System.out.println("consume2 and topic is"+ tm.getText());

                        } catch (JMSException e) {

                               e.printStackTrace();

                       }

                    }

             }});//消费者2增加消息监听

创建了2个消费者,都订阅了名字为"LzyTopic"的topic。接下来的代码在创建一个生产者,同样也是指定topic。

producer = session.createProducer(topic);//和消费者同样的topic

for (int i = 0; i <5; i++) {

      TextMessage tm=session.createTextMessage("Message"+i);

      producer.send(tm);//发送消息

}

打印结果如下:

consume1 and topic isMessage0

consume2 and topic isMessage0

consume1 and topic isMessage1

consume2 and topic isMessage1

consume1 and topic isMessage2

consume2 and topic isMessage2

consume1 and topic isMessage3

consume2 and topic isMessage3

你可能感兴趣的:(消息中间件学习之JMS(3))