一、ActiveMQ是什么?
ActiveMQ是Apache推出的一款开源的,完全支持JMS1.1和J2EE1.4规范的JMS Provider实现的消息中间件(Message Oriented Middleware,MOM)。
MOM大白话解释:我们最开始做的项目都是一个工程完成的,但后期随着业务的变更,需要把核心功能抽取出来单独作为一个项目,同时也减少了依赖。这个项目可能被多个系统进行调用,这个时候我们就需要一个第三方消息中间件来做消息传递,使个系统解耦。
ActiveMQ就是MOM的实现。主要用来减小项目依赖,同时提供异步调用作用。
二、ActiveMQ安装
1.从http://activemq.apache.org/activemq-5143-release.html下载最新版本的ActiveMQ
2.直接解压,然后拷贝到你要安装的位置就OK了。
3.到ActiveMQ/bin目录下 ./activemq start
或启动并指定日志文件./activemq start >/tmp/activemqlog
4.检查是否已经启动
ActiveMQ默认采用61616端口提供JMS服务,使用8161端口提供管理控制台服务,执行以下命令便可以检验是否已经成功启动ActiveMQ服务。
a)查看61616端口是否打开:netstat -an | grep 61616
b)直接查看控制台输出或者日志文件
c)直接访问ActiveMQ管理页面http://localhost:8161/admin/ 默认用户名密码admin/admin
d)关闭ActiveMQ可以使用./activemq stop
e)暴力关闭:ps -ef | grep activemq 然后kill -9 端口号 干掉。
三、基本使用
1.配置Maven所需要的依赖,示例如下:
pom配置文件
<dependency> <groupId>org.apache.activemq</groupId> <artifactId>activemq-all</artifactId> <version>5.9.0</version> </dependency> <dependency> <groupId>org.apache.xbean</groupId> <artifactId>xbean-spring</artifactId> <version>3.16</version> </dependency>
发送端:
public class JmsSend { public static void main(String[] args) { //创建链接工厂 ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://localhost:61616"); //创建连接 Connection connection = connectionFactory.createConnection(); //启动连接 connection.start(); //创建一个会话 //Boolean.TRUE 要不要使用事务 //Session.AUTO_ACKNOWLEDGE 消息怎么确认 Session session = connection.createSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE); //创建目的地 //my-queue 队列名字 自己取名字 Destination destination = session.createQueue("my-queue"); //创建生产者 发送消息的人 MessageProducer producer = session.createProducer(destination); for(int i=0; i<3; i++) { //封装具体的消息 TextMessage message = session.createTextMessage("message--"+i); Thread.sleep(1000); //通过消息生产者发出消息 producer.send(message); } //事务提交 session.commit(); //关闭会话 session.close(); //关闭连接 connection.close(); } }
接收端
public class JmsReceiver { public static void main(String[] args) throws Exception { ConnectionFactory cf = new ActiveMQConnectionFactory("tcp://localhost:61616"); Connection connection = cf.createConnection(); connection.start(); final Session session = connection.createSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE); //创建消息目的地 //my-queue跟发送的名字要一致 Destination destination = session.createQueue("my-queue"); //创建接收端 MessageConsumer consumer = session.createConsumer(destination); int i=0; while(i<3) { i++; TextMessage message = (TextMessage) consumer.receive(); session.commit(); System.out.println("收到消 息:" + message.getText()); } session.close(); connection.close(); } }