ActiveMq基于queue的代码实现

activeMq是一种消息中间件,在很多电商的系统中都有用到!

我们是基于windows的测试,所以之前应该启动服务端!


image.png

启动完成之后进行代码的测试!

package com.activemq;

import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

public class Producer {   //生产者

    public static void main(String[] args) throws JMSException {
        ActiveMQConnectionFactory activeMQConnectionFactory=new ActiveMQConnectionFactory("tcp://localhost:61616");
        Connection connection = activeMQConnectionFactory.createConnection();
        connection.start();
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        Queue queue = session.createQueue("huangshuai_Message");
        MessageProducer producer = session.createProducer(queue);
        TextMessage textMessage = session.createTextMessage("HS生产了一条消息");
        System.out.println(textMessage.getText());
        producer.send(textMessage);
        producer.close();
        session.close();
        connection.close();
    }
}

image.png

然后我们启动消费者,接受消息!

package com.activemq;

import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;
import java.io.IOException;

public class Consumer {
    public static void main(String[] args) throws JMSException, IOException {
        //1.创建连接工厂
        ConnectionFactory connectionFactory=new ActiveMQConnectionFactory("tcp://localhost:61616");
        //2.获取连接
        Connection connection = connectionFactory.createConnection();
        //3.启动连接
        connection.start();
        //4.获取session  (参数1:是否启动事务,参数2:消息确认模式)
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        //创建队列对象
        Queue queue = session.createQueue("huangshuai_Message");
        //创建消费者
        MessageConsumer consumer = session.createConsumer(queue);
        //进行事件的监听
        consumer.setMessageListener(new MessageListener() {
            public void onMessage(Message message) {
                TextMessage textMessage=(TextMessage) message;
                try {
                    System.out.println("接收到消息"+textMessage.getText());
                } catch (JMSException e) {
                    e.printStackTrace();
                }
            }
        });
        System.in.read();
        //关闭资源
        consumer.close();
        session.close();
        connection.close();
    }
}

image.png

image.png

至此,我们就完成了基于队列的基本测试!

你可能感兴趣的:(ActiveMq基于queue的代码实现)