ActiveMQ_01、queue入门案例
一、启动activeMQ
启动activeMQ后,可以用浏览器进入监控界面:
http://localhost:8161/admin
初始账号、密码:admin/admin
二、pom依赖
<dependency>
<groupId>org.apache.activemq</groupId>
<artifactId>activemq-all</artifactId>
<version>5.14.3</version>
</dependency>
三、生产者代码
默认的连接端口是61616,tcp协议
账号、密码仍然是admin/admin
connectionFactory创建connection并start
connection创建session
然后是由session来操作,session创建队列test1、生产者、消息
最后由生产者发送消息
package com.demo.queue01;
import org.apache.activemq.ActiveMQConnectionFactory;
import javax.jms.*;
/**
* 生产
*/
public class QueueProduce {
public static void main(String[] args) throws JMSException {
ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("admin", "admin", "tcp://localhost:61616");
Connection connection = factory.createConnection();
connection.start();
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
Queue queue = session.createQueue("test1");
TextMessage message = session.createTextMessage("ppap");
MessageProducer producer = session.createProducer(queue);
producer.send(message);
producer.close();
session.close();
connection.close();
}
}
四、消费者代码
类似的,
connectionFactory创建connection并start
connection创建session
然后session获取队列queue1、创建消费者
最后由消费者获取消息
我试了下,消费时必须调用connection.start(),否则哪怕有消息也会一直阻塞在哪里.
但是生产者哪怕不调用connection.start(),仍然可以成功发送消息;原因暂时不明;
package com.demo.queue01;
import org.apache.activemq.ActiveMQConnectionFactory;
import javax.jms.*;
/**
* 消费者
*/
public class QueueConsumer {
public static void main(String[] args) throws JMSException {
ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("admin", "admin", "tcp://localhost:61616");
Connection connection = factory.createConnection();
connection.start();
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
Queue queue = session.createQueue("test1");
MessageConsumer consumer = session.createConsumer(queue);
Message message = consumer.receive();
if (message instanceof TextMessage) {
TextMessage tm = (TextMessage) message;
System.out.println(tm.getText());
}
consumer.close();
session.close();
connection.close();
}
}