【ActiveMQ】消息中间件activeMq搭建一
一、下载activeMq5.15.2 http://activemq.apache.org/
二、项目maven引入相关jar包
<!-- 消息中间件 -->
<dependency>
<groupId>org.apache.activemq</groupId>
<artifactId>activemq-all</artifactId>
<version>5.15.2</version>
</dependency>
三、发送者代码
Send.java-------------------------------------------------------------------------------------------------------------
package cn.temptation.test;
import java.util.concurrent.TimeUnit;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
import org.apache.activemq.ActiveMQConnectionFactory;
public class Send {
public static void main(String[] args) throws Exception {
ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(ActiveMQConnectionFactory.DEFAULT_USER,
ActiveMQConnectionFactory.DEFAULT_PASSWORD, "tcp://localhost:61616");
Connection connection = connectionFactory.createConnection();
connection.start();
Session session = connection.createSession(Boolean.FALSE, Session.AUTO_ACKNOWLEDGE);
Destination destination = session.createQueue("first");
MessageProducer producer = session.createProducer(null);
for (int i = 0; i < 100; i++) {
TextMessage msg = session.createTextMessage("我是消息内容" + i);
producer.send(destination, msg);
TimeUnit.SECONDS.sleep(1);
}
if (connection != null) {
connection.close();
}
}
}
四、消费者代码
Receive.java----------------------------------------------------------------------------------------------------------
package cn.temptation.test;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.MessageConsumer;
import javax.jms.Session;
import javax.jms.TextMessage;
import org.apache.activemq.ActiveMQConnectionFactory;
public class Receive {
public static void main(String[] args) throws Exception {
ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(ActiveMQConnectionFactory.DEFAULT_USER,
ActiveMQConnectionFactory.DEFAULT_PASSWORD, "tcp://localhost:61616");
Connection connection = connectionFactory.createConnection();
connection.start();
Session session = connection.createSession(Boolean.FALSE, Session.AUTO_ACKNOWLEDGE);
Destination destination = session.createQueue("first");
MessageConsumer consumer = session.createConsumer(destination);
while (true) {
TextMessage msg = (TextMessage) consumer.receive();
System.out.println("消息数据:" + msg.getText());
}
}
}
五、运行C:\Users\user\Desktop\apache-activemq-5.15.2\bin\win64\activemq.bat
同时打开http://localhost:8161/admin/ 查看消息发送、接收情况
六、运行消费函数、运行发送函数,查看效果