ActiveMQ

1.安装:
地址:https://activemq.apache.org/components/classic/download/
解压后:cmd activemq start (依赖java环境)

image.png

视图:http://localhost:8161/admin/
image.png

2. java编码实现ActiveMQ通讯

  1. IDEA新建maven工程
  2. 依赖

    org.apache.xbean
    xbean-spring
    3.16

  1. 测试(消息生产)
public class Jmsproduce {
    private static final String ACTIVEMQ_URL = "tcp://localhost:61616";
    private static final String QUEUE_NAME = "queue01";

    public static void main(String[] args) throws JMSException {

        // 1. 创建连接工厂,使用默认用户名和密码
        ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory(ACTIVEMQ_URL);
        // 2. 由连接工厂创建连接
        Connection connection = activeMQConnectionFactory.createConnection();
        // 3. 启动
        connection.start();
        // 4. 创建会话(事务,签收)
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        // 5. 创建目的地(以队列)
        Queue queue = session.createQueue(QUEUE_NAME);
        // 6. 创建消息生产者
        MessageProducer producer = session.createProducer(queue);
        // 7. 通过使用MessageProducer生产三条消息发送到MQ队列
        for(int i = 0;i < 3;i++){
            // 8.创建消息
            TextMessage textMessage = session.createTextMessage("msg:" + i);
            // 9. 发送
            producer.send(textMessage);
        }
        // 10. 关闭资源
        producer.close();
        session.close();
        connection.close();
        System.out.println("Msg send OK!");
    }
}
image.png
  1. 测试(消息接收)
public class JmsConsumer {
    private static final String ACTIVEMQ_URL = "tcp://localhost:61616";
    private static final String QUEUE_NAME = "queue01";

    public static void main(String[] args) throws JMSException {

        // 1. 创建连接工厂,使用默认用户名和密码
        ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory(ACTIVEMQ_URL);
        // 2. 由连接工厂创建连接
        Connection connection = activeMQConnectionFactory.createConnection();
        // 3. 启动
        connection.start();
        // 4. 创建会话(事务,签收)
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        // 5. 创建目的地(以队列)
        Queue queue = session.createQueue(QUEUE_NAME);
        // 6. 创建消费者
        MessageConsumer consumer = session.createConsumer(queue);
        // 7. 接收消息
        while (true){
            TextMessage textMessage = (TextMessage)consumer.receive();
            if(textMessage != null){
                System.out.println("consumer get :"+textMessage.getText());
            }else{
                break;
            }
        }
        // 8. 关闭资源
        consumer.close();
        session.close();
        connection.close();
    }
}
image.png

你可能感兴趣的:(ActiveMQ)