ActiveMQ消息系统

ActiveMQ 是Apache所提供的一个开源消息系统,完全采用Java实现,能够很好的支持J2EE提出的JMS(Java Message Service)规范。JMS即Java消息服务,是一组Java应用程序接口,他提供消息的创建、发送、接收、读取等一系列服务。JMS定义一组公共应用程序接口和相应语法,类似Java的数据库的统一访问接口JDBC。

特性

1、 多种语言和协议编写客户端。语言: Java、C、C++、C#、Ruby、Perl、Python、PHP。应用协议:OpenWire、Stomp REST、WS Notification、XMPP、AMQP
2、完全支持JMS1.1和J2EE 1.4规范 (持久化,XA消息,事务)
3、对Spring的支持,ActiveMQ可以很容易内嵌到使用Spring的系统里面去,而且也支持Spring2.0的特性
4、通过了常见J2EE服务器(如 Geronimo、JBoss 4、GlassFish、WebLogic)的测试,其中通过JCA 1.5 resource adaptors的配置,可以让ActiveMQ可以自动的部署到任何兼容J2EE 1.4 商业服务器上
5、支持多种传送协议:in-VM、TCP、SSL、NIO、UDP、JGroups、JXTA
6、支持通过JDBC和journal提供高速的消息持久化
7、从设计上保证了高性能的集群,客户端-服务器,点对点
8、支持Ajax
9、支持与Axis的整合
10、可以很容易得调用内嵌JMS provider,进行测试

安装

下载安装

可以在Apache ActiveMQ官网下载,apache-activemq-5.12.0windon版本或者linux版本,解压缩,目录如下所示:
ActiveMQ目录结构

解压启动

进入bin目录,使用activemq.bat双击启动(windows用户可以选择系统位数[/bin/win64/activemq.bat],如果你是linux的话,就用命令行的发送去启动),如果一切顺利,你就会看见类似下面的信息:
ActiveMQ启动成功界面
如果你看到这个,那么恭喜你成功了。如果你启动看到了异常信息:

Caused by: java.io.IOException: Failed to bind to server socket: tcp://0.0.0.0:61616?maximumConnections=1000&wireformat.maxFrameSize=104857600 due to: java.net.SocketException: Unrecognized Windows Sockets error: 0: JVM_Bind

那么我告诉你,很不幸,你的端口被占用了。接下来你大概想知道是哪个程序占用了你的端口,并kill掉该进程或服务。或者你要尝试修改ActiveMQ的默认端口61616(ActiveMQ使用的默认端口是61616),在大多数情况下,占用61616端口的是Internet Connection Sharing (ICS) 这个Windows服务,你只需停止它就可以启动ActiveMQ了。

访问管理员界面

启动成功就可以访问管理员界面:http://localhost:8161/admin,默认用户名和密码admin/admin。如果你想修改用户名和密码的话,在conf/jetty-realm.properties中修改即可。
ActiveMQ首页
其中在导航菜单中,Queues是队列方式消息。Topics是主题方式消息。Subscribers消息订阅监控查询。Connections可以查看链接数,分别可以查看xmpp、ssl、stomp、openwire、ws和网络链接。Network是网络链接数监控。Send可以发送消息数据。

#消息示例

消息三种类型

ActiveMQ消息类型

点对点方式(point-to-point)

ActiveMQ点对点
点对点的消息发送方式主要建立在 Message Queue,Sender,reciever上,Message Queue 存贮消息,Sneder 发送消息,receive接收消息.具体点就是Sender Client发送Message Queue ,而 receiver Cliernt从Queue中接收消息和”发送消息已接受”到Quere,确认消息接收。消息发送客户端与接收客户端没有时间上的依赖,发送客户端可以在任何时刻发送信息到Queue,而不需要知道接收客户端是不是在运行

发布/订阅 方式(publish/subscriber Messaging)

ActiveMQ发布订阅
发布/订阅方式用于多接收客户端的方式.作为发布订阅的方式,可能存在多个接收客户端,并且接收端客户端与发送客户端存在时间上的依赖。一个接收端只能接收他创建以后发送客户端发送的信息。作为subscriber ,在接收消息时有两种方法,destination的receive方法,和实现message listener 接口的onMessage 方法。

ActiveMQ接收和发送消息基本流程

ActiveMQ消息发布流程图

发送消息的基本步骤:

(1)、创建连接使用的工厂类JMS ConnectionFactory
(2)、使用管理对象JMS ConnectionFactory建立连接Connection,并启动
(3)、使用连接Connection 建立会话Session
(4)、使用会话Session和管理对象Destination创建消息生产者MessageSender
(5)、使用消息生产者MessageSender发送消息

消息接收者从JMS接受消息的步骤

(1)、创建连接使用的工厂类JMS ConnectionFactory
(2)、使用管理对象JMS ConnectionFactory建立连接Connection,并启动
(3)、使用连接Connection 建立会话Session
(4)、使用会话Session和管理对象Destination创建消息接收者MessageReceiver
(5)、使用消息接收者MessageReceiver接受消息,需要用setMessageListener将MessageListener接口绑定到MessageReceiver消息接收者必须实现了MessageListener接口,需要定义onMessage事件方法。

代码示例

添加jar包

我添加的是activemq-all-5.12.0.jar,或者添加activemq-client-5.12.0.jar、slf4j-api-1.7.10.jar、hawtbuf-1.11.jar

基于Queue队列的点对点消息发送

Producer类-生产者

package cn.xiaoyu.activemq.p2p;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.DeliveryMode;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.ObjectMessage;
import javax.jms.Session;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;
/**
 * 消息的生产者    点对点消息传输模式(point-to-point)
 */
public class Producer {
    public static void main(String[] args) throws JMSException {
        // 连接工厂,JMS用它来创建连接
        ConnectionFactory connectionFactory = 
                new ActiveMQConnectionFactory(ActiveMQConnection.DEFAULT_USER,ActiveMQConnection.DEFAULT_PASSWORD,"tcp://localhost:61616");
        // JMS客户端到JMS Producter的链接
        Connection conn = connectionFactory.createConnection();
        conn.start();
        System.out.println("生产者启动成功!");
        /**
         *  发送或者接收消息的线程
         *  这儿两个参数,
         *  第一个表示的是是否采用事务消息,如果是true的话,那么消息的提交有commit自动处理,消息回滚由rollback处理
         *  第二表示消息的确认方式:
         *      Session.AUTO_ACKNOWLEDGE  Session自动确定所接受的消息 
         *      Session.CLIENT_ACKNOWLEDGE  客户端通过调用消息确认方法来确认所收到的消息
         *      Session.DUPS_OK_ACKNOWLEDGE  Session将会懒惰确认消息,即不会立即确认消息,这样可能会导致消息的重复投递
         */
        Session session = conn.createSession(Boolean.TRUE,Session.AUTO_ACKNOWLEDGE);
        // 消息的目的地
        Destination destination = session.createQueue("MsgQueue");
        // 消息的发送者
        MessageProducer producer = session.createProducer(destination);
        // 设置不持久化
        producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);

        /**
         * 创建消息对象,并发送消息
         * 这儿支持的消息类型有:
         *     简单文本(TextMessage),可序列化对象(ObjectMessage),键值对(MapMessage)
         *  字节流(BytesMessage),流(StreamMessage),无有效负载消息(Message)
         */
        ObjectMessage message = session.createObjectMessage("Hello ActiveMQ");
        producer.send(message);

        session.commit();
    }
}

Consumer类-消费者

package cn.xiaoyu.activemq.p2p;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageConsumer;
import javax.jms.ObjectMessage;
import javax.jms.Session;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

/**
 * 消息的消费者   点对点消息传输模式(point-to-point)
 */
public class Consumer {
    public static void main(String[] args) throws JMSException {
        // 连接工厂,JMS用它来创建连接
        ConnectionFactory connectionFactory = 
                new ActiveMQConnectionFactory(ActiveMQConnection.DEFAULT_USER,ActiveMQConnection.DEFAULT_PASSWORD,"tcp://localhost:61616");
        // JMS客户端到JMS Producter的链接
        Connection conn = connectionFactory.createConnection();
        conn.start();
        System.out.println("消费者启动成功!");
        // 发送或者接收消息的线程
        Session session = conn.createSession(Boolean.FALSE,Session.AUTO_ACKNOWLEDGE);
        // 消息的目的地
        Destination destination = session.createQueue("MsgQueue");
        // 消息的发送者
        MessageConsumer consumer = session.createConsumer(destination);

        while(true){
            // 設置接受者接收時間
            ObjectMessage message = (ObjectMessage) consumer.receive(10000);
            if(null != message){
                String msg = (String) message.getObject();
                System.out.println(msg);
            }else{
                break;
            }
        }

    }
}

基于Topic主题的订阅发布

Producer类-生产者

package cn.xiaoyu.activemq.pubsub;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.DeliveryMode;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.ObjectMessage;
import javax.jms.Session;
import javax.jms.Topic;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;
/**
 * 消息的生产者  发布订阅模式(publish/subscribe)
 */
public class Producer {
    public static void main(String[] args) throws JMSException {
        // 连接工厂,JMS用它来创建连接
        ConnectionFactory connectionFactory = 
                new ActiveMQConnectionFactory(ActiveMQConnection.DEFAULT_USER,ActiveMQConnection.DEFAULT_PASSWORD,"tcp://localhost:61616");
        // JMS客户端到JMS Producter的链接
        Connection conn = connectionFactory.createConnection();
        conn.start();
        System.out.println("生产者启动成功!");
        /**
         *  发送或者接收消息的线程
         *  这儿两个参数,
         *  第一个表示的是是否采用事务消息,如果是true的话,那么消息的提交有commit自动处理,消息回滚由rollback处理
         *  第二表示消息的确认方式:
         *      Session.AUTO_ACKNOWLEDGE  Session自动确定所接受的消息 
         *      Session.CLIENT_ACKNOWLEDGE  客户端通过调用消息确认方法来确认所收到的消息
         *      Session.DUPS_OK_ACKNOWLEDGE  Session将会懒惰确认消息,即不会立即确认消息,这样可能会导致消息的重复投递
         */
        Session session = conn.createSession(Boolean.FALSE,Session.AUTO_ACKNOWLEDGE);
        // 消息的目的地
        Topic topic = session.createTopic("MsgTopic");
        // 消息的发送者
        MessageProducer producer = session.createProducer(topic);
        // 设置不持久化
        producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);

        /**
         * 创建消息对象,并发送消息
         * 这儿支持的消息类型有:
         *     简单文本(TextMessage),可序列化对象(ObjectMessage),键值对(MapMessage)
         *  字节流(BytesMessage),流(StreamMessage),无有效负载消息(Message)
         */
        ObjectMessage message = session.createObjectMessage("Hello ActiveMQ");
        producer.send(message);
    }
}

Consumer类-消费者

package cn.xiaoyu.activemq.pubsub;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.ObjectMessage;
import javax.jms.Session;
import javax.jms.Topic;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;
/**
 * 消息的消费者  发布订阅模式(publish/subscribe)
 */
public class Consumer {
    public static void main(String[] args) throws JMSException {
        // 连接工厂,JMS用它来创建连接
        ConnectionFactory connectionFactory = 
                new ActiveMQConnectionFactory(ActiveMQConnection.DEFAULT_USER,ActiveMQConnection.DEFAULT_PASSWORD,"tcp://localhost:61616");
        // JMS客户端到JMS Producter的链接
        Connection conn = connectionFactory.createConnection();
        conn.start();
        System.out.println("消费者启动成功!");
        // 发送或者接收消息的线程
        Session session = conn.createSession(Boolean.FALSE,Session.AUTO_ACKNOWLEDGE);
        // 消息的目的地
        Topic topic = session.createTopic("MsgTopic");
        // 消息的发送者
        MessageConsumer consumer = session.createConsumer(topic);

        consumer.setMessageListener(new MessageListener() {
            @Override
            public void onMessage(Message msg) {
                ObjectMessage om = (ObjectMessage) msg;
                try {
                    System.out.println(om.getObject());
                } catch (JMSException e) {}
            }
        });
    }
}

整合spring框架

添加jar包

消息发送者

package com.hoo.mq.spring.support;

import java.util.Date;
import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.Session;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;

/**
 * <b>function:</b> Spring JMSTemplate 消息发送者
 */
public class Sender {

    public static void main(String[] args) {
        ApplicationContext ctx = new FileSystemXmlApplicationContext("classpath:applicationContext-*.xml");
        JmsTemplate jmsTemplate = (JmsTemplate) ctx.getBean("jmsTemplate");

        jmsTemplate.send(new MessageCreator() {
            public Message createMessage(Session session) throws JMSException {
                MapMessage message = session.createMapMessage();
                message.setString("message", "current system time: " + new Date().getTime());

                return message;
            }
        });
    }
}

消息接受者

package com.hoo.mq.spring.support;

import java.util.Map;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import org.springframework.jms.core.JmsTemplate;

/**
 * <b>function:</b> Spring JMSTemplate 消息接收者
 */
public class Receiver {

    @SuppressWarnings("unchecked")
    public static void main(String[] args) {
        ApplicationContext ctx = new FileSystemXmlApplicationContext("classpath:applicationContext-*.xml");  

        JmsTemplate jmsTemplate = (JmsTemplate) ctx.getBean("jmsTemplate");  
        while(true) {  
            Map<String, Object> map =  (Map<String, Object>) jmsTemplate.receiveAndConvert();  

            System.out.println("收到消息:" + map.get("message"));  
        }  
    }
}

Spring配置文件

这里主要是用到了JmsTemplate这个消息模板,这个对象在spring的IoC容器中管理,所以要从spring的容器上下文中获取。下面看看spring的配置文件applicationContext-beans.xml内容:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.1.xsd">

    <!-- 连接池  -->
    <bean id="pooledConnectionFactory" class="org.apache.activemq.pool.PooledConnectionFactory" destroy-method="stop">  
        <property name="connectionFactory">  
            <bean class="org.apache.activemq.ActiveMQConnectionFactory">  
                <property name="brokerURL" value="tcp://localhost:61616" />  
            </bean>  
        </property>  
    </bean>  

    <!-- 连接工厂 -->
    <bean id="activeMQConnectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">  
        <property name="brokerURL" value="tcp://localhost:61616" />  
    </bean>  

    <!-- 配置消息目标 -->
    <bean id="destination" class="org.apache.activemq.command.ActiveMQQueue">  
        <!-- 目标,在ActiveMQ管理员控制台创建 http://localhost:8161/admin/queues.jsp -->
        <constructor-arg index="0" value="hoo.mq.queue" />  
    </bean>  

    <!-- 消息模板 -->
    <bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">  
        <property name="connectionFactory" ref="activeMQConnectionFactory" />  
        <property name="defaultDestination" ref="destination" />  
        <property name="messageConverter">  
            <bean class="org.springframework.jms.support.converter.SimpleMessageConverter" />
        </property>  
    </bean>  
</beans>

这里的整合就比较简单了,如果你是web工程,那你在需要用jms的时候,只需用注入jmsTemplate即可。

参考

ActiveMQ 即时通讯服务 浅析
activemq的几种基本通信方式总结