Embedded ActiveMQ broker in java
Guide package
<dependency>
<groupId>org.apache.activemq</groupId>
<artifactId>activemq-all</artifactId>
<version>5.15.9</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.7</version>
</dependency>
Embedded broker startup method
package com.mq;
import org.apache.activemq.broker.BrokerService;
public class EebedBroker {
public static void main(String[] args) throws Exception {
BrokerService brokerService=new BrokerService();
brokerService.setUseJmx(true);
brokerService.addConnector("tcp://localhost:61616");
brokerService.start();
}
}
The producers and consumers for testing
consumer
package com.mq;
import org.apache.activemq.ActiveMQConnectionFactory;
import javax.jms.*;
public class QueueProducer {
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("queue_test");
//创建消息生产者
MessageProducer messageProducer=session.createProducer(queue);
//创建消息对象
for (int i=0;i<=3;i++){
String msg = "千里之行,始于足下";
Message message = session.createTextMessage(msg);
//发送消息
messageProducer.send(message);
}
//关闭所有连接
messageProducer.close();
session.close();
connection.close();
}
}
consumer
package com.mq;
import org.apache.activemq.ActiveMQConnectionFactory;
import javax.jms.*;
import java.io.IOException;
public class QueueConsumer {
public static void main(String[] args) throws JMSException, IOException {
//创建连接工厂
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("queue_test");
//创建消息消费者
MessageConsumer messageConsumer=session.createConsumer(queue);
// 消息消费,使用监听器
messageConsumer.setMessageListener((message)->{
if(message instanceof TextMessage){
String text = null;
try {
text = ((TextMessage) message).getText();
} catch (JMSException e) {
e.printStackTrace();
}
System.err.println("收到的消息是:" + text);
}
});
System.in.read();
messageConsumer.close();
session.close();
connection.close();
}
}
Test
to start the embedded broker
restart producers
finally start consumers (consumers received the message).