activemq安装及使用
1. 去官网下载activemq : http://activemq.apache.org/activemq-5120-release.html
2.该版本不是最新版本,最新版本启动报错,原因未知,所以用过的是 :5.12版本
3.将文件解压:运行
4.登录服务器:http://localhost:8161/admin/index.jsp,默认用户名、密码为:admin
5.启动成功
6.编写消息生产者
package com.xuzhiwen.test; import javax.jms.Connection; import javax.jms.ConnectionFactory; import javax.jms.Destination; import javax.jms.JMSException; import javax.jms.MessageProducer; import javax.jms.Session; import javax.jms.TextMessage; import org.apache.activemq.ActiveMQConnectionFactory; public class SendMessage { public static String url = "tcp://localhost:61616"; public static String queueName = "queue1"; public static void main(String[] args) throws JMSException { ConnectionFactory connectionFactory = null; Connection connection = null; Session session = null; Destination destination = null; MessageProducer messageProducer = null; connectionFactory = new ActiveMQConnectionFactory(url); connection = connectionFactory.createConnection(); connection.start(); session = connection.createSession(Boolean.FALSE, Session.AUTO_ACKNOWLEDGE); destination = session.createQueue(queueName); messageProducer = session.createProducer(destination); for (int i = 0; i < 100; i++) { TextMessage tm = session.createTextMessage("生产者发送消息"+i); messageProducer.send(tm); System.out.println("【"+queueName+"】"+tm.getText()); } connection.close(); }
7.运行后结果如下:
8.在查看服务器:
9.编写消费者:
package com.xuzhiwen.test; import javax.jms.Connection; import javax.jms.ConnectionFactory; import javax.jms.Destination; import javax.jms.JMSException; import javax.jms.Message; import javax.jms.MessageConsumer; import javax.jms.MessageListener; import javax.jms.MessageProducer; import javax.jms.Session; import javax.jms.TextMessage; import org.apache.activemq.ActiveMQConnectionFactory; public class GetMessage { public static String url = "tcp://localhost:61616"; public static String queueName = "queue1"; public static void main(String[] args) throws JMSException { ConnectionFactory connectionFactory = null; Connection connection = null; Session session = null; Destination destination = null; MessageConsumer messageConsumer = null; connectionFactory = new ActiveMQConnectionFactory(url); connection = connectionFactory.createConnection(); connection.start(); session = connection.createSession(Boolean.FALSE, Session.AUTO_ACKNOWLEDGE); destination = session.createQueue(queueName); messageConsumer = session.createConsumer(destination); messageConsumer.setMessageListener(new MessageListener() { @Override public void onMessage(Message msg) { TextMessage tm = (TextMessage) msg; try { System.out.println(tm.getText()); } catch (JMSException e) { e.printStackTrace(); } } }); } }
10.运行后结果如下:
11.查看服务器:
注意:
如果运行两个消费者,再运行发送者,结果如下:
消费者1:
消费者2: