简介:

Apache ActiveMQ ™ 是最流行最强大的开源消息及继承模式服务器。i

Apache ActiveMQ 速度快,支持多种语言的客户端及代理,可便捷的使用企业集成模式,完整支持JMS1.1及JEE1.4 ,符合 Apache2.0 Licence。

0.下载地址

https://activemq.apache.org/download.html

1.解压并启动activemq服务(需根据系统的不同选择不同的启动文件)

/apache-activemq-5.13.1/bin/macosx/activemq start

2.登录activemq服务器进行查看

地址:http://localhost:8161/

点击[Manage ActiveMQ broker]登录查看详细数据,默认用户名密码admin/admin

3.ActiviteMQ消息有3种形式

JMS 公共

点对点域

发布/订阅域

ConnectionFactory

QueueConnectionFactory

TopicConnectionFactory

Connection

QueueConnection

TopicConnection

Destination

Queue

Topic

Session

QueueSession

TopicSession

MessageProducer

QueueSender

TopicPublisher

MessageConsumer

QueueReceiver

TopicSubscriber

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

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

3.1 发送消息的基本步骤:

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

3.2 接收消息的基本步骤

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

4.代码示例

创建eclipse项目

/apache-activemq-5.13.1/lib下倒入所需jar包

4.1 通用jms示例

public class Sender {
    private static final int SEND_NUMBER=5;

    public static void main(String[] args){
        ConnectionFactory connectionFactory;
        Connection connection =null;
        Session session;
        Destination destination;
        MessageProducer producer;

        connectionFactory=new ActiveMQConnectionFactory(
                ActiveMQConnection.DEFAULT_USER,
                ActiveMQConnection.DEFAULT_PASSWORD,
                "tcp://localhost:61616");
        try{
            connection = connectionFactory.createConnection();
            connection.start();

            session=connection.createSession(Boolean.TRUE,
                    Session.AUTO_ACKNOWLEDGE);

            destination=session.createQueue("JMeterQueue");

            producer=session.createProducer(destination);
            producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
            sendMessage(session,producer);
            session.commit();
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            try{
                if(null!=connection){
                    connection.close();
                }
            }catch(Throwable ignore){

            }
        }
    }

    public static void sendMessage(Session session,MessageProducer producer) throws JMSException{
        for(int i=1;i<SEND_NUMBER;i++){
            TextMessage message=session.createTextMessage("ActiveMq send "+i);
            System.out.println("ActiveMq send "+i);
            producer.send(message);
        }
    }
}
public class Receiver {
    public static void main(String[] args){
        ConnectionFactory connectionFactory ;
        Connection connection=null;
        Session session;
        Destination destination;
        MessageConsumer consumer;

        connectionFactory = new ActiveMQConnectionFactory(
                ActiveMQConnection.DEFAULT_USER,
                ActiveMQConnection.DEFAULT_PASSWORD,
                "tcp://localhost:61616");
        try{
            connection = connectionFactory.createConnection();
            connection.start();
            session=connection.createSession(Boolean.TRUE,
                    Session.AUTO_ACKNOWLEDGE);
            destination=session.createQueue("JMeterQueue");
            consumer=session.createConsumer(destination);
            while(true){
                TextMessage message=(TextMessage)consumer.receive(10000);

                if(null !=message){
                    System.out.println("Message receive "+ message.getText());
                }else{
                    break;
                }
            }
            session.commit();
            //session.commit 之后,Messages Enqueued 中的消息才会被被消费掉,Messages Dequeued 才会增加;
            //如果不commit,Messages Dequeued会一直为0,每次启动receiver后都会受到所有未消费的消息
        }catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != connection)
                    connection.close();
            } catch (Throwable ignore) {
            }
        }
    }
}

4.2 p2p示例

public class QueueSender {

    // 发送次数
    public static final int SEND_NUM = 5;
    // tcp 地址
    public static final String BROKER_URL = "tcp://localhost:61616";
    // 目标,在ActiveMQ管理员控制台创建
    public static final String DESTINATION = "mq.p2p.queue";

    public static void run() throws Exception {
        QueueConnection connection = null;
        QueueSession session = null;
        try {
            // 创建链接工厂
            QueueConnectionFactory factory = new ActiveMQConnectionFactory(ActiveMQConnection.DEFAULT_USER, ActiveMQConnection.DEFAULT_PASSWORD, BROKER_URL);
            // 通过工厂创建一个连接
            connection = factory.createQueueConnection();
            // 启动连接
            connection.start();
            // 创建一个session会话
            session = connection.createQueueSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);
            // 创建一个消息队列
            Queue queue = session.createQueue(DESTINATION);
            // 创建消息发送者
            javax.jms.QueueSender sender = session.createSender(queue);
            // 设置持久化模式
            sender.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
            sendMessage(session, sender);
            // 提交会话
            session.commit();

        } catch (Exception e) {
            throw e;
        } finally {
            // 关闭释放资源
            if (session != null) {
                session.close();
            }
            if (connection != null) {
                connection.close();
            }
        }
    }

    public static void sendMessage(QueueSession session, javax.jms.QueueSender sender) throws Exception {
        for (int i = 0; i < SEND_NUM; i++) {
            String message = "发送消息第" + (i + 1) + "条";
            Message msg=session.createTextMessage(message);
            sender.send(msg);
        }
    }

    public static void main(String[] args) throws Exception {
        QueueSender.run();
    }
}
public class QueueReceiver {

    // tcp 地址
    public static final String BROKER_URL = "tcp://localhost:61616";
    // 目标,在ActiveMQ管理员控制台创建
    public static final String TARGET = "mq.p2p.queue";

    public static void run() throws Exception {
        QueueConnection connection = null;
        QueueSession session = null;
        try {
            // 创建链接工厂
            QueueConnectionFactory factory = new ActiveMQConnectionFactory(ActiveMQConnection.DEFAULT_USER, ActiveMQConnection.DEFAULT_PASSWORD, BROKER_URL);
            // 通过工厂创建一个连接
            connection = factory.createQueueConnection();
            // 启动连接
            connection.start();
            // 创建一个session会话
            session = connection.createQueueSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);
            // 创建一个消息队列
            Queue queue = session.createQueue(TARGET);
            // 创建消息制作者
            javax.jms.QueueReceiver receiver = session.createReceiver(queue);

            receiver.setMessageListener(new MessageListener() {
                public void onMessage(Message msg) {
                    if (msg != null) {
                        TextMessage map = (TextMessage) msg;
                        try {
                            System.out.println(map.getText());
                        } catch (JMSException e) {
                            e.printStackTrace();
                        }
                    }
                }
            });
            // 休眠100ms再关闭
            Thread.sleep(1000 * 20); 

            // 提交会话
            session.commit();

        } catch (Exception e) {
            throw e;
        } finally {
            // 关闭释放资源
            if (session != null) {
                session.close();
            }
            if (connection != null) {
                connection.close();
            }
        }
    }

    public static void main(String[] args) throws Exception {
        QueueReceiver.run();
    }
}

4.3 订阅示例

public class TopicSender {

    // 发送次数
    public static final int SEND_NUM = 5;
    // tcp 地址
    public static final String BROKER_URL = "tcp://localhost:61616";
    // 目标,在ActiveMQ管理员控制台创建
    public static final String DESTINATION = "mq.topic";

    public static void run() throws Exception {
        TopicConnection connection = null;
        TopicSession session = null;
        try {
            // 创建链接工厂
            TopicConnectionFactory factory = new ActiveMQConnectionFactory(ActiveMQConnection.DEFAULT_USER, ActiveMQConnection.DEFAULT_PASSWORD, BROKER_URL);
            // 通过工厂创建一个连接
            connection = factory.createTopicConnection();
            // 启动连接
            connection.start();
            // 创建一个session会话
            session = connection.createTopicSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);
            // 创建一个消息队列
            Topic topic = session.createTopic(DESTINATION);
            // 创建消息发送者
            TopicPublisher publisher = session.createPublisher(topic);
            // 设置持久化模式
            publisher.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
            sendMessage(session, publisher);
            // 提交会话
            session.commit();

        } catch (Exception e) {
            throw e;
        } finally {
            // 关闭释放资源
            if (session != null) {
                session.close();
            }
            if (connection != null) {
                connection.close();
            }
        }
    }

    public static void sendMessage(TopicSession session, TopicPublisher publisher) throws Exception {
        for (int i = 0; i < SEND_NUM; i++) {
            String message = "发送消息第" + (i + 1) + "条";
            TextMessage msg =session.createTextMessage(message);
            publisher.send(msg);
        }
    }

    public static void main(String[] args) throws Exception {
        TopicSender.run();
    }
}
public class TopicReceiver {

    // tcp 地址
    public static final String BROKER_URL = "tcp://localhost:61616";
    // 目标,在ActiveMQ管理员控制台创建
    public static final String TARGET = "mq.topic";

    public static void run() throws Exception {
        TopicConnection connection = null;
        TopicSession session = null;
        try {
            // 创建链接工厂
            TopicConnectionFactory factory = new ActiveMQConnectionFactory(ActiveMQConnection.DEFAULT_USER, ActiveMQConnection.DEFAULT_PASSWORD, BROKER_URL);
            // 通过工厂创建一个连接
            connection = factory.createTopicConnection();
            // 启动连接
            connection.start();
            // 创建一个session会话
            session = connection.createTopicSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);
            // 创建一个消息队列
            Topic topic = session.createTopic(TARGET);
            // 创建消息制作者
            TopicSubscriber subscriber = session.createSubscriber(topic);

            subscriber.setMessageListener(new MessageListener() {
                public void onMessage(Message msg) {
                    System.out.println(msg);
                }
            });
            // 休眠100ms再关闭
            Thread.sleep(1000 * 20); 

            // 提交会话
            session.commit();

        } catch (Exception e) {
            throw e;
        } finally {
            // 关闭释放资源
            if (session != null) {
                session.close();
            }
            if (connection != null) {
                connection.close();
            }
        }
    }

    public static void main(String[] args) throws Exception {
        TopicReceiver.run();
    }
}

ActiveMQ应用(1)-安装及示例的更多相关文章

  1. neo4j安装与示例

    Neo4j有两种访问模式:服务器模式和嵌入模式参考,下面主要讲windows下这两种模式的配置与访问示例 1 Windows下Neo4j服务器模式安装与示例 安装: 1.下载Neo4j,我下载的版本是 ...

  2. ActiveMQ下载与安装(Linux环境下进行)

    下载 官方网站:http:activemq.apache.org/ 安装(liunx) 1.将apache-activemq-5.12.0-bin.tar.gz(liunx环境下的压缩包)上传至服务器 ...

  3. .NET Core R2安装及示例教程

    .NET Core R2安装及示例教程 Install for Windows - Visual Studio 2015 1 Download Visual Studio 2015 Make sure ...

  4. 基准测试-jmeter压力测试activeMQ之一环境安装配置

    jmeter压力测试activeMQ 摘要:linux(CentOS)单机activeMQ安装.window(2008Server)Jmeter配置activeMQ包.Jmeter配置linux监控 ...

  5. ActiveMQ笔记(1):编译、安装、示例代码

    一.编译 虽然ActiveMQ提供了发布版本,但是建议同学们自己下载源代码编译,以后万一有坑,还可以尝试自己改改源码. 1.1 https://github.com/apache/activemq/r ...

  6. ActiveMQ 简介与安装

    一. 概述与介绍 ActiveMQ 是Apache出品,最流行的.功能强大的即时通讯和集成模式的开源服务器.ActiveMQ 是一个完全支持JMS1.1和J2EE 1.4规范的 JMS Provide ...

  7. ActiveMQ:初见&安装试运行

    官网:http://activemq.apache.org/ ActiveMQ是一个消息中间件,在大型互联网应用中有广泛的使用. 当前最新版本:5.15.4,发布于2018-05-22,开源.Apac ...

  8. ActiveMQ笔记之安装(Linux)

    1. 基本概念 MQ(MessageQueue),消息队列,是一个消息接收和转发的容器. Apache ActiveMQ是一个JMS Provider实现. 2. 安装 从官网下载安装包: wget ...

  9. node.js express安装及示例网站搭建

    1.首先肯定是要安装Node.JS windows cmd依次输入如下命令: cd C:\Program Files\nodejs\ npm install -g expressnpm install ...

随机推荐

  1. laravel框架入门

    本文摘自网络,个人感觉写的很不错,决定收藏一下纯属本人学习之用 本文介绍如何开始使用 Laravel. 读完本文,你将学到: 如何安装 Laravel,新建 Laravel 程序,如何连接数据库: L ...

  2. shell编程之测试和判断

    一.测试 程序运行中经常需要根据实际情况来运行特定的命令或代码段.比如判断某个文件或目录是否存在,如果文件或目录不存在,可能首先创建文件或目录.举例说,要判断文件/var/log/mlocate文件是 ...

  3. 如何在Ubuntu18.04(Bionic Beaver)系统安装Teamviewer远程控制软件

    首先,打开TeamViewer的下载页面,下载Debian/Ubuntu的Deb安装包. 这里有64位和32位安装包选项.可以在Terminal(终端)中输入uname -a 查看自己系统版本是64位 ...

  4. 【Codeforces 115D】Unambiguous Arithmetic Expression

    Codeforces 115 D 题意:给一个没有括号的表达式,问有多少种添加括号的方法使得这是一个合法的表达式?输入可能有正负号.加减乘除.数字. 思路1: 这是不能过的\(naive\)的\(dp ...

  5. C语言程序设计II—第五周教学

    第五周教学总结(25/3-31/3) 教学内容 本周的教学内容为:第七章 数组 7.3 字符串. 课前准备 在博客园发布作业:2019春第五周作业 第四周作业讲解视频:A Programing Vid ...

  6. SkylineGlobe的PopupMessage里面嵌入的网页如何与主页面交互通讯

    1.主页面调用PopupMessage,如果需要传值,就是普通的页面间的传值就可以实现了. a.html页面调用PopupMessage创建方法,url传入b.html?x=111&y=22; ...

  7. 关于PCB开窗

    如果走220V,那么线宽一点,一般高电压下面不覆铜 https://blog.csdn.net/zhy295006359/article/details/77412566 假设感觉需要走大电流,那么就 ...

  8. Codechef STREDUC Reduce string Trie、bitset、区间DP

    VJ传送门 简化题意:给出一个长度为\(l\)的模板串\(s\)与若干匹配串\(p_i\),每一次你可以选择\(s\)中的一个出现在集合\(\{p_i\}\)中的子串将其消去,其左右分成的两个串拼接在 ...

  9. Luogu3067 平衡的奶牛群 Meet in the middle

    题意:给出$N$个范围在$[1,10^8]$内的整数,问有多少种取数方案使得取出来的数能够分成两个和相等的集合.$N \leq 20$ 发现爆搜是$O(3^N)$的,所以考虑双向搜索. 先把前$3^\ ...

  10. (转)Putty server refused our key的三种原因和解决方法

    原文 上一篇博文介绍了使用Putty免密码登录,我后面试了另一台虚拟机,结果putty显示错误server refused our key(在linux下则表现为仍需要输入密码),搜索了下,很多人都遇 ...