消息中间件ActiveMQ入门学习笔记

本文介绍了Apache ActiveMQ两种消息模式:Topic广播和Queue分食。在Topic模式下,多个消费者可以接收到所有消息,实现广播效果;而在Queue模式中,消息被消费者平均分配,实现消息分食。通过示例代码展示了如何创建Producer和Consumer,并解释了相关配置及工作原理。
摘要由CSDN通过智能技术生成

消息中间件activemq有两种模式:topic广播、queue分食,两者代码很类似,主要区别是创建消息主题时会声明是topic还是queue

环境准备

  1. 软件安装

     https://activemq.apache.org/下载并解压至本地
    
  2. activemq服务开启

     xx\apache-activemq-5.16.2\bin\win64\activemq.bat双击即可开启
    
  3. 服务启动截图
    在这里插入图片描述

  4. 进入activemq的消息监控页面

     打开http://127.0.0.1:8161/并输入admin/admin
     activemq服务的默认端口是8161
    

代码示例

  • 有问题的pom引入

    全部引入会有slf4j冲突
    SLF4J: Class path contains multiple SLF4J bindings.

      <dependency>
          <groupId>org.apache.activemq</groupId>
          <artifactId>activemq-all</artifactId>
          <version>5.15.9</version>
      </dependency>
    
  • 推荐引入方式

    单独引入

      <dependency>
          <groupId>org.apache.activemq</groupId>
          <artifactId>activemq-core</artifactId>
          <version>5.7.0</version>
      </dependency>
      <dependency>
          <groupId>org.apache.activemq</groupId>
          <artifactId>activemq-pool</artifactId>
      </dependency>
      <!-- 使用到了hutool -->
      <dependency>
          <groupId>cn.hutool</groupId>
          <artifactId>hutool-all</artifactId>
          <version>4.3.1</version>
      </dependency>
    
  • 测试端口是否可达的工具类

    import cn.hutool.core.util.NetUtil;
    import javax.swing.*;
    public class ActiveMQUtil {
        public static void main(String[] args) {
            checkServer();
        }
        public static void checkServer() {
            //activemq服务开启后默认端口为8161
            if (NetUtil.isUsableLocalPort(8161)) {
                JOptionPane.showMessageDialog(null, "ActiveMQ服务器未启动");
                System.exit(1);
            } else {
                System.out.println("ActiveMQ服务器已启动");
            }
        }
    }
    
  • 模式1topic广播

    创建一个producer和AB两个consumer,先运行两个consumer再运行producer,可以观察控制台情况:producer发送100个消息,AB两个consumer分别全部接收了这100个消息

    import javax.jms.Connection;
    import javax.jms.ConnectionFactory;
    import javax.jms.Destination;
    import javax.jms.JMSException;
    import javax.jms.MessageProducer;
    import javax.jms.Session;
    import javax.jms.TextMessage;
    import message.activemq.ActiveMQUtil;
    import org.apache.activemq.ActiveMQConnectionFactory;
    /**
     * 先运行多个消费者,再运行生产者,可以看到多个消费者都拿到了同样的消息
     */
    public class TopicProducer {
        //配置服务地址和端口
        private static final String url = "tcp://127.0.0.1:61616";
        //这次发送的消息名称
        private static final String topicName = "topic_style";
        public static void main(String[] args) throws JMSException {
            //检查activemq服务是否开启
            ActiveMQUtil.checkServer();
            //创建ConnectionFactory并绑定url
            ConnectionFactory factory = new ActiveMQConnectionFactory(url);
            //创建Connection
            Connection connection = factory.createConnection();
            //启动连接
            connection.start();
            //创建Session
            Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            //使用session创建主题topic
            Destination destination = session.createTopic(topicName);
            //创建消息生产者
            MessageProducer producer = session.createProducer(destination);
            for (int i = 0; i < 100; i++) {
                //创建消息
                TextMessage textMessage = session.createTextMessage("主题消息-" + i);
                //发送消息
                producer.send(textMessage);
                System.out.println("发送主题topic消息:" + textMessage.getText());
            }
            //关闭连接
            producer.close();
            session.close();
            connection.close();
        }
    }
    

    import cn.hutool.core.util.RandomUtil;
    import message.activemq.ActiveMQUtil;
    import org.apache.activemq.ActiveMQConnectionFactory;
    import javax.jms.*;
    public class TopicConsumerA {
        //配置服务地址和端口
        private static final String url = "tcp://127.0.0.1:61616";
        //这次消费的消息名称
        private static final String topicName = "topic_style";
        //定义当前消费者名称
        private static final String consumerName = "consumer-" + RandomUtil.randomString(5);
        public static void main(String[] args) throws JMSException {
            //检查activemq服务是否开启
            ActiveMQUtil.checkServer();
            System.out.printf("消费者启动了:%s%n", consumerName);
            //创建ConnectionFactory并绑定url
            ConnectionFactory factory = new ActiveMQConnectionFactory(url);
            //创建Connection
            Connection connection = factory.createConnection();
            //启动连接
            connection.start();
            //创建Session
            Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            //使用session创建主题topic
            Destination destination = session.createTopic(topicName);
            //创建消息生产者
            MessageConsumer consumer = session.createConsumer(destination);
            //消费者创建监听器
            consumer.setMessageListener(new MessageListener() {
                public void onMessage(Message arg0) {
                    TextMessage textMessage = (TextMessage) arg0;
                    try {
                        System.out.println(consumerName + "=>接收消息:" + textMessage.getText());
                    } catch (JMSException e) {
                        e.printStackTrace();
                    }
    
                }
            });
            //consumer.close();
            //session.close();
            //connection.close();
        }
    }
    
  • 模式2queue分食

    创建ABC三个consumer,运行后发现producer发送了100个消息,被ABC平均消费了,所以我理解为分食

    import javax.jms.Connection;
    import javax.jms.ConnectionFactory;
    import javax.jms.Destination;
    import javax.jms.JMSException;
    import javax.jms.MessageProducer;
    import javax.jms.Session;
    import javax.jms.TextMessage;
    import message.activemq.ActiveMQUtil;
    import org.apache.activemq.ActiveMQConnectionFactory;
    /**
     * 先运行多个消费者,再运行生产者,可以看到消息被多个消费者均分消费了
     */
    public class QueueProducer {
        //配置服务地址和端口
        private static final String url = "tcp://127.0.0.1:61616";
        //这次发送的消息名称
        private static final String topicName = "queue_style";
        public static void main(String[] args) throws JMSException {
            //检查activemq服务是否开启
            ActiveMQUtil.checkServer();
            //创建ConnectionFactory并绑定url
            ConnectionFactory factory = new ActiveMQConnectionFactory(url);
            //创建Connection
            Connection connection = factory.createConnection();
            //启动连接
            connection.start();
            //创建Session
            Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            //使用session创建队列
            Destination destination = session.createQueue(topicName);
            //创建消息生产者
            MessageProducer producer = session.createProducer(destination);
            for (int i = 0; i < 100; i++) {
                //创建消息
                TextMessage textMessage = session.createTextMessage("队列消息=>" + i);
                //发送消息
                producer.send(textMessage);
                System.out.println("发送队列queue消息:" + textMessage.getText());
            }
            //关闭连接
            producer.close();
            session.close();
            connection.close();
        }
    }
    

    import cn.hutool.core.util.RandomUtil;
    import message.activemq.ActiveMQUtil;
    import org.apache.activemq.ActiveMQConnectionFactory;
    import javax.jms.*;
    public class QueueConsumerA {
        //配置服务地址和端口
        private static final String url = "tcp://127.0.0.1:61616";
        //这次发送的消息名称
        private static final String topicName = "queue_style";
        //定义当前消费者名称
        private static final String consumerName = "consumer-" + RandomUtil.randomString(5);
        public static void main(String[] args) throws JMSException {
            //检查activemq服务是否开启
            ActiveMQUtil.checkServer();
            System.out.printf("消费者启动了:%s%n", consumerName);
            //创建ConnectionFactory并绑定url
            ConnectionFactory factory = new ActiveMQConnectionFactory(url);
            //创建Connection
            Connection connection = factory.createConnection();
            //启动连接
            connection.start();
            //创建Session
            Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            //使用session创建队列
            Destination destination = session.createQueue(topicName);
            //创建消息消费者
            MessageConsumer consumer = session.createConsumer(destination);
            //消费者创建监听器
            consumer.setMessageListener(new MessageListener() {
                public void onMessage(Message arg0) {
                    TextMessage textMessage = (TextMessage) arg0;
                    try {
                        System.out.println(consumerName + "=>接收消息:" + textMessage.getText());
                    } catch (JMSException e) {
                        e.printStackTrace();
                    }
                }
            });
            //consumer.close();
            //session.close();
            //connection.close();
        }
    }
    
  • 监控页面信息

    topic模式,AB共两个消费者,producer发送的100个消息被AB分别接收,所以消息出列为200

    在这里插入图片描述

    queue模式,ABC共三个消费者,可以看到消息出列为100,消息被分食,参考下面A的日志

    在这里插入图片描述
    在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值