ActiveMQ 学习

ActiveMQ 学习,第1张

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)效果图,执行完消费者的请求之后

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5690175.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存