消息队列activeMQ之(queue类型)的小demo(学习笔记之三)

1、建立pom项目添加pom依赖
<dependency>
  <groupId>org.apache.activemq</groupId>
  <artifactId>activemq-all</artifactId>
  <version>5.11.2</version>
</dependency>
2、创建man方法向MQ写入队列消息
package com.demo;



import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

/**
 * Created by luwan on 2018/4/14.
 */
public class App {
    public static void main(String[] args) throws JMSException {
        // 发送一个队列模式的消息
        ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://192.168.223.131:61616");
        Connection connection = connectionFactory.createConnection();
        connection.start();

        // 创建会话
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

        // 消息对象,由于mq是支持很多个业务功能的,每一个业务功能都放在不同的路径下面
        Queue queue = session.createQueue("office-queue");

        // 消息内容
        TextMessage textMessage = session.createTextMessage("我渴了,来杯水...");

        // 发送端
        MessageProducer producer = session.createProducer(queue);

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

        // 关闭连接
        producer.close();
        session.close();
        connection.close();

    }
}
3、查看MQ的消息
4、另一个comsumer接受MQ消息

package macomsumer;

import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

/**
 * Created by luwan on 2018/4/14.
 */
public class App {
    public static void main(String[] args) throws Exception {
        // 创建连接
        ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://192.168.223.131:61616");
        Connection connection = connectionFactory.createConnection();
        connection.start();

        // 创建 会话
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

        // 创建消息对象
        Queue queue = session.createQueue("office-queue");

        // 接收端
        MessageConsumer consumer = session.createConsumer(queue);

        // 接收消息
        consumer.setMessageListener(new MessageListener() {
            @Override
            public void onMessage(Message message) {
                // 打印结果
                TextMessage textMessage = (TextMessage) message;
                String text = "";
                try {
                    text = textMessage.getText();
                } catch (JMSException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                System.err.println(听到了" + text + ",积极的响应了要求。。。");
            }
        });
        // 等待接收消息
        System.in.read();
    }
}

4.客户端表格的字段含义

                        挂起的消息                         在监听的人数             入队的消息              消费的消息


1 队列模式的消息,默认永久保存

2 订阅模式的消息,默认不永久保存,如果需要永久保存,需要为consumer在服务器上初始化一个永久保存的存储空间




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章