栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 前沿技术 > 大数据 > 大数据系统

ActiveMQ 学习

ActiveMQ 学习

1. 打开activeMQ客户端

2. 生产者 1)代码
package com.sunny.producer;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;


public class ProducerTest {
    public static void main(String[] args) throws JMSException {
        //获取MQ连接工厂
        ConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory(ActiveMQConnection.DEFAULT_USER,
                ActiveMQConnection.DEFAULT_PASSWORD,"tcp://127.0.0.1:61616");
        //创建连接
        Connection connection = activeMQConnectionFactory.createConnection();

        // 启动连接
        connection.start();
        //创建会话工厂
        Session session = connection.createSession(Boolean.FALSE, Session.AUTO_ACKNOWLEDGE);
        //创建队列
        Queue destination = session.createQueue("sunny_MQ01");
        //创建消息生产者
        MessageProducer producer = session.createProducer(destination);

        for (int i = 1; i <=5; i++){
            System.out.println("我是消息生产者产出的消息"+i);
            sendMsg(session,producer,"我是消息生产者产出的消息"+i);
        }
        System.out.println("生产者生产消息完毕");
    }

    public static  void sendMsg(Session session, MessageProducer  producer, String n) throws JMSException {
        TextMessage ts = session.createTextMessage(n);
        producer.send(ts);

    }
}

2)效果图,执行完生产者应用之后

3. 消费者

1)代码

package com.sunny.producer;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;


public class ConsumerTest {



    public static void main(String[] args) throws JMSException {
        //获取MQ连接工厂
        ConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory(ActiveMQConnection.DEFAULT_USER,
                ActiveMQConnection.DEFAULT_PASSWORD,"tcp://127.0.0.1:61616");
        //创建连接
        Connection connection = activeMQConnectionFactory.createConnection();

        // 启动连接
        connection.start();
        //创建会话工厂
        Session session = connection.createSession(Boolean.FALSE, Session.AUTO_ACKNOWLEDGE);
        //创建队列
        Queue destination = session.createQueue("sunny_MQ01");
        //创建消息消费者
        MessageConsumer consumer = session.createConsumer(destination);
        while (true){
            TextMessage receive = (TextMessage) consumer.receive();
            if (null != receive){
                String text = receive.getText();
                System.out.println("我是消费者,正在消费"+text);
            }else{
                break;
            }

        }
        System.out.println("消费者消费消息完毕");
    }

    public ConsumerTest() throws JMSException {
    }
}

 2)效果图,执行完消费者的请求之后

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/689670.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号