zoukankan      html  css  js  c++  java
  • 深入掌握JMS(五):实战Topic[转]

    与Queue不同的是,Topic实现的是发布/订阅模型,在下面的例子中,启动2个消费者共同监听一个Topic,然后循环给这个Topic中发送多个 消息。

    import javax.jms.Connection;
    import javax.jms.JMSException;
    import javax.jms.Message;
    import javax.jms.MessageConsumer;
    import javax.jms.MessageListener;
    import javax.jms.MessageProducer;
    import javax.jms.Session;
    import javax.jms.TextMessage;
    import javax.jms.Topic;

    import org.apache.activemq.ActiveMQConnectionFactory;
    import org.apache.activemq.command.ActiveMQTopic;


    public class TopicTest {

    public static void main(String[] args) throws Exception {
    ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost");

    Connection connection = factory.createConnection();
    connection.start();

    //创建一个Topic
    Topic topic= new ActiveMQTopic("testTopic");
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

    //注册消费者1
    MessageConsumer comsumer1 = session.createConsumer(topic);
    comsumer1.setMessageListener(new MessageListener(){
    public void onMessage(Message m) {
    try {
    System.out.println("Consumer1 get " + ((TextMessage)m).getText());
    } catch (JMSException e) {
    e.printStackTrace();
    }
    }
    });

    //注册消费者2
    MessageConsumer comsumer2 = session.createConsumer(topic);
    comsumer2.setMessageListener(new MessageListener(){
    public void onMessage(Message m) {
    try {
    System.out.println("Consumer2 get " + ((TextMessage)m).getText());
    } catch (JMSException e) {
    e.printStackTrace();
    }
    }

    });

    //创建一个生产者,然后发送多个消息。
    MessageProducer producer = session.createProducer(topic);
    for(int i=0; i<10; i++){
    producer.send(session.createTextMessage("Message:" + i));
    }
    }

    }

    运行后得到下面的输出结果:

    Consumer1 get Message:0
    Consumer2 get Message:0
    Consumer1 get Message:1
    Consumer2 get Message:1
    Consumer1 get Message:2
    Consumer2 get Message:2
    Consumer1 get Message:3
    Consumer2 get Message:3
    Consumer1 get Message:4
    Consumer2 get Message:4
    Consumer1 get Message:5
    Consumer2 get Message:5
    Consumer1 get Message:6
    Consumer2 get Message:6
    Consumer1 get Message:7
    Consumer2 get Message:7
    Consumer1 get Message:8
    Consumer2 get Message:8
    Consumer1 get Message:9
    Consumer2 get Message:9

    说明每一个消息都会被所有的消费者消费。 
  • 相关阅读:
    剑指offer--38.左旋转字符串
    剑指offer--37.和为S的两个数字
    剑指offer--35.数组中只出现一次的数字
    剑指offer--34.数字在排序数组中出现的次数
    剑指offer--33.丑数
    剑指offer--36.整数中1出现的次数(从1到n整数中1出现的次数)
    剑指offer--32.把数组排成最小的数
    剑指offer--31.二叉树中和为某一值的路径
    剑指offer--30.二叉搜索树的后序遍历序列
    剑指offer--29.从上往下打印二叉树
  • 原文地址:https://www.cnblogs.com/jjj250/p/2524015.html
Copyright © 2011-2022 走看看