activemq

结构图activemq

依赖activemq

package com.activemq.activemqdemo.p2p;

import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

public class JMSProducer {

    public static final String ACTIVE_URL = "tcp://127.0.0.1:61616";
    // 队列名称
    public static final String QUEUE_NAME = "index";

    public static void main(String[] args) throws JMSException {
        // 1)获取工厂 ConnectionFactory,使用摸摸人的用户名和密码admin/admin, 指定URL
        ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(ACTIVE_URL);
        // 2)获取连接
        Connection connection = connectionFactory.createConnection();
        // 3)启动连接
        connection.start();
        // 4)创建Session ,参数transacted:事务,acknowledgeMode响应模式
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        // 5)创建目的地: 队列
        Queue queue = session.createQueue(QUEUE_NAME);
        // 6)创建生产者,参数destination表示目的地---Queue
        MessageProducer messageProducer = session.createProducer(queue);
        // 7)发送消息
        for (int i = 1 ; i <= 3; i++){
            TextMessage textMessage = session.createTextMessage("index队列中的消息:" + i);
            messageProducer.send(textMessage);
        }
        // 8)关闭资源
        messageProducer.close();
        session.close();
        connection.close();

    }

}
package com.activemq.activemqdemo.p2p;

import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

public class JMSConsumer {

    public static final String ACTIVE_URL = "tcp://127.0.0.1:61616";
    // 队列名称
    public static final String QUEUE_NAME = "index";

    public static void main(String[] args) throws JMSException {
        // 1)获取工厂 ConnectionFactory,使用摸摸人的用户名和密码admin/admin, 指定URL
        ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(ACTIVE_URL);
        // 2)获取连接
        Connection connection = connectionFactory.createConnection();
        // 3)启动连接
        connection.start();
        // 4)创建Session ,参数transacted:事务,acknowledgeMode响应模式
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        // 5)创建目的地: 队列
        Queue queue = session.createQueue(QUEUE_NAME);
        // 6)创建消费者,
        MessageConsumer messageConsumer = session.createConsumer(queue);
        // 7)接收消息: 获取队列中的所有消息,消费者一直接收消息
        while (true){
            TextMessage msg = (TextMessage) messageConsumer.receive();
            if (msg != null){
                // 接收到消息了
                System.out.println("JMSConsumer接收到消息了:"+msg.getText());
            }else {
                // 队列中的消息全部接收完毕
                System.out.println("-----消息接收完成----");
                break;
            }
        }


    }
}

相关推荐