activemq 话题模式(三)

生产者

package com.test.producermq;

import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

/**
 * @Title: MessageProducer
 * @ProjectName activemq
 * @date 2019/11/89:49
 */
public class MessageProducer2 {
    //定义ActivMQ的连接地址
    private static final String ACTIVEMQ_URL = "tcp://127.0.0.1:61616";
    //定义发送消息的主题名称
    private static final String TOPIC_NAME = "MyTopicMessage";

    public static void main(String[] args) throws JMSException {
        //1创建连接工厂
        ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory(ACTIVEMQ_URL);
        //2创建连接
        Connection connection = activeMQConnectionFactory.createConnection();
        //3打开连接
        connection.start();
        //4创建会话
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        //5创建队列目标
        Destination destination = session.createTopic(TOPIC_NAME);
        //6创建一个生产者
        javax.jms.MessageProducer producer = session.createProducer(destination);
        //创建模拟100个消息
        for (int i = 1; i <= 100; i++) {
            TextMessage message = session.createTextMessage("当前message是(主题模型):" + i);
            //发送消息
            producer.send(message);
            //在本地打印消息
            System.out.println("我现在发的消息是:" + message.getText());
        }
        //关闭连接
        connection.close();
    }
}

 消费者

package com.test.consumemq;

import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

/**
 * @Title: MessageConsumer
 * @ProjectName activemq
 * @date 2019/11/89:56
 */
public class MessageConsumer2 {
    //定义ActivMQ的连接地址
    private static final String ACTIVEMQ_URL = "tcp://127.0.0.1:61616";
    //定义发送消息的队列名称
    private static final String TOPIC_NAME = "MyTopicMessage";
    public static void main(String[] args) throws JMSException {
        //1创建连接工厂
        ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory(ACTIVEMQ_URL);
        //2创建连接
        Connection connection = activeMQConnectionFactory.createConnection();
        //3打开连接
        connection.start();
        //4创建会话
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        //5创建队列目标
        Destination destination = session.createTopic(TOPIC_NAME);
        //6创建消费者
        javax.jms.MessageConsumer consumer = session.createConsumer(destination);
        //创建消费的监听
        consumer.setMessageListener(new MessageListener() {
            @Override
            public void onMessage(Message message) {
                TextMessage textMessage = (TextMessage) message;
                try {
                    System.out.println("2获取消息:" + textMessage.getText());
                } catch (JMSException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}

如果消费者是在生产者产生消息之后来的,那么是不会对之前的消息进行消费的

       所有订阅者都会受到发布者的消息

相关推荐