使用 ActiveMQ 示例


企业中各项目中相互协作的时候可能用得到消息通知机制。比如有东西更新了,可以通知做索引。

在 Java 里有 JMS 的多个实现。其中 apache 下的 ActiveMQ 就是不错的选择。还有一个比较热的是 RabbitMQ (是 erlang 语言实现的)。这里示例下使用 ActiveMQ

用 ActiveMQ 最好还是了解下 JMS

JMS 公共 点对点域 发布/订阅域
ConnectionFactory QueueConnectionFactory TopicConnectionFactory
Connection QueueConnection TopicConnection
Destination Queue Topic
Session QueueSession TopicSession
MessageProducer QueueSender TopicPublisher
MessageConsumer QueueReceiver TopicSubscriber

JMS 定义了两种方式:Quere(点对点);Topic(发布/订阅)。

ConnectionFactory 是连接工厂,负责创建Connection。

Connection 负责创建 Session。

Session 创建 MessageProducer(用来发消息) 和 MessageConsumer(用来接收消息)。

Destination 是消息的目的地。

详细的可以网上找些 JMS 规范(有中文版)。

下载 apache-activemq-5.3.0。http://activemq.apache.org/download.html,解压,然后双击 bin/activemq.bat。运行后,可以在 http://localhost:8161/admin 观察。也有
demo, http://localhost:8161/demo。把 activemq-all-5.3.0.jar 加入 classpath。

Jms 发送 代码:

  1. public static void main(String[] args) throws Exception {
  2. ConnectionFactory connectionFactory = new ActiveMQConnectionFactory();
  3. Connection connection = connectionFactory.createConnection();
  4. connection.start();
  5. Session session = connection.createSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);
  6. Destination destination = session.createQueue("my-queue");
  7. MessageProducer producer = session.createProducer(destination);
  8. ; i<3; i++) {
  9. MapMessage message = session.createMapMessage();
  10. message.setLong("count", new Date().getTime());
  11. );
  12. //通过消息生产者发出消息
  13. producer.send(message);
  14. }
  15. session.commit();
  16. session.close();
  17. connection.close();
  18. }

Jms 接收代码:

  1. public static void main(String[] args) throws Exception {
  2. ConnectionFactory connectionFactory = new ActiveMQConnectionFactory();
  3. Connection connection = connectionFactory.createConnection();
  4. connection.start();
  5. final Session session = connection.createSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);
  6. Destination destination = session.createQueue("my-queue");
  7. MessageConsumer consumer = session.createConsumer(destination);
  8. /*//listener 方式
  9. consumer.setMessageListener(new MessageListener() {
  10. public void onMessage(Message msg) {
  11. MapMessage message = (MapMessage) msg;
  12. //TODO something....
  13. System.out.println("收到消息:" + new Date(message.getLong("count")));
  14. session.commit();
  15. }
  16. });
  17. Thread.sleep(30000);
  18. */
  19. ;
  20. ) {
  21. i++;
  22. MapMessage message = (MapMessage) consumer.receive();
  23. session.commit();
  24. //TODO something....
  25. System.out.println("收到消息:" + new Date(message.getLong("count")));
  26. }
  27. session.close();
  28. connection.close();
  29. }

启动 JmsReceiver 和 JmsSender 可以在看输出三条时间信息。当然 Jms 还指定有其它格式的数据,如 TextMessage

结合 Spring 的 JmsTemplate 方便用:

xml:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
  4. <!-- 在非 web / ejb 容器中使用 pool 时,要手动 stop,spring 不会为你执行 destroy-method 的方法
  5. <bean id="jmsFactory" class="org.apache.activemq.pool.PooledConnectionFactory" destroy-method="stop">
  6. <property name="connectionFactory">
  7. <bean class="org.apache.activemq.ActiveMQConnectionFactory">
  8. <property name="brokerURL" value="tcp://localhost:61616" />
  9. </bean>
  10. </property>
  11. </bean>
  12. -->
  13. <bean id="jmsFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
  14. <property name="brokerURL" value="tcp://localhost:61616" />
  15. </bean>
  16. <bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
  17. <property name="connectionFactory" ref="jmsFactory" />
  18. <property name="defaultDestination" ref="destination" />
  19. <property name="messageConverter">
  20. <bean class="org.springframework.jms.support.converter.SimpleMessageConverter" />
  21. </property>
  22. </bean>
  23. <bean id="destination" class="org.apache.activemq.command.ActiveMQQueue">
  24. <constructor-arg index="0" value="my-queue" />
  25. </bean>
  26. </beans>

sender:

  1. public static void main(String[] args) {
  2. ApplicationContext ctx = new FileSystemXmlApplicationContext("classpath:app*.xml");
  3. JmsTemplate jmsTemplate = (JmsTemplate) ctx.getBean("jmsTemplate");
  4. jmsTemplate.send(new MessageCreator() {
  5. public Message createMessage(Session session) throws JMSException {
  6. MapMessage mm = session.createMapMessage();
  7. mm.setLong("count", new Date().getTime());
  8. return mm;
  9. }
  10. });
  11. }

receiver:

  1. public static void main(String[] args) {
  2. ApplicationContext ctx = new FileSystemXmlApplicationContext("classpath:app*.xml");
  3. JmsTemplate jmsTemplate = (JmsTemplate) ctx.getBean("jmsTemplate");
  4. while(true) {
  5. Map<String, Object> mm =  (Map<String, Object>) jmsTemplate.receiveAndConvert();
  6. System.out.println("收到消息:" + new Date((Long)mm.get("count")));
  7. }
  8. }

注意:直接用 Jms 接口时接收了消息后要提交一下,否则下次启动接收者时还可以收到旧数据。有了 JmsTemplate 就不用自己提交 session.commit() 了。如果使用了 PooledConnectionFactory 要把 apache-activemq-5.3.0\lib\optional\activemq-pool-5.3.0.jar 加到 classpath

参考资料:

Hello ActiveMQ

Spring2.5整合ActiveMQ 5.2

spring-support

JMS 相关资料

原文出处:http://blog.chenlb.com/2010/01/activemq-hello.html

使用 ActiveMQ 示例的更多相关文章

  1. Java ActiveMQ 示例

    所需引入Jar包: jms-1.1.jar activemq-all-5.15.0.jar 生产者 package com.mousewheel.demo; import javax.jms.Conn ...

  2. 分布式-信息方式-ActiveMQ示例

    实战 代码如下: 信息生产者 package test.mq.helloword; import javax.jms.Connection; import javax.jms.ConnectionFa ...

  3. C#---初学ActiveMQ中间件

    本篇文章只适合跟我一样的初学者,因为现阶段的我们只想者怎么实现功能,不太会去考虑潜在异常.从上周开始优化公司的调控系统,原先采取的都是通过操作数据库去实现功能,客户体验效果不佳,经过领导决定是用中间件 ...

  4. 消息队列之 ActiveMQ(山东数漫江湖)

    简介 ActiveMQ 特点 ActiveMQ 是由 Apache 出品的一款开源消息中间件,旨在为应用程序提供高效.可扩展.稳定.安全的企业级消息通信. 它的设计目标是提供标准的.面向消息的.多语言 ...

  5. 消息队列之 ActiveMQ

    简介 ActiveMQ 特点 ActiveMQ 是由 Apache 出品的一款开源消息中间件,旨在为应用程序提供高效.可扩展.稳定.安全的企业级消息通信. 它的设计目标是提供标准的.面向消息的.多语言 ...

  6. 分布式--ActiveMQ 消息中间件(一) https://www.jianshu.com/p/8b9bfe865e38

    1. ActiveMQ 1). ActiveMQ ActiveMQ是Apache所提供的一个开源的消息系统,完全采用Java来实现,因此,它能很好地支持J2EE提出的JMS(Java Message ...

  7. Active MQ C#实现

    原文链接: Active MQ C#实现 内容概要 主要以源码的形式介绍如何用C#实现同Active MQ 的通讯.本文假设你已经正确安装JDK1.6.x,了解Active MQ并有一定的编程基础. ...

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

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

  9. ActiveMQ入门示例

    1.ActiveMQ下载地址 http://activemq.apache.org/download.html 2.ActiveMQ安装,下载解压之后如下目录

随机推荐

  1. WebAPI异常捕捉处理,结合log4net日志(webapi框架)

    一:异常捕捉处理 首先,在我们需要区分controller的类型.是全部基层controller,还是Apicontroller.(当然一般API框架,用的都是Apicontroller).两者异常处 ...

  2. 复杂json解析方式[GsonFormat]

    针对开发人员来讲,善于用工具,事半功倍. 干货: 1.IntelliJ IDEA 通过GsonFormat插件将JSONObject格式的String 解析成实体 插件地址:https://plugi ...

  3. Matlab高级教程_第一篇:Matlab基础知识提炼_06

    第十一节:图形操作 第十二节:文件的IO操作个格式化输出

  4. 2019年icpc上海网络赛 B Light bulbs (分块、差分)

    https://nanti.jisuanke.com/t/41399 题目大意: 有n个灯,m次操作,每次修改[l,r]内的灯,(off - on ,on - off),问最后有几盏灯亮着. 换种说法 ...

  5. Educational Codeforces Round 55 (Rated for Div. 2)E

    题:https://codeforces.com/contest/1082/problem/E 题意:给出n个数和一个数c,只能操作一次将[L,R]之间的数+任意数,问最后该序列中能存在最多多少个c ...

  6. rsync+nfs+sersync实战案例

    回顾: 1.rsync 统一备份各个服务器的配置文件或重要文件 系统配置文件 日志文件 系统日志文件 messages.secure.cron 服务日志文件 access_log.access.log ...

  7. mock简单的json返回

    针对非常简单的json返回串,我们也不一定非得通过freemarker模板的方式来构造返回数据,这里看实际的需求,如果返回的内容是固定的,而且json又非常简单,我们也可以直接写在程序里面,下面的接口 ...

  8. vue项目中的elementUI的table组件导出成excel表

    1.安装依赖:npm install --save xlsx file-saver 2.在放置需要导出功能的组件中引入 import FileSaver from 'file-saver' impor ...

  9. Pandas Series 对象的loc与iloc区别

    import pandas as pd temp = pd.Series([,,,,]) loc用法: temp.loc[:] 0 1 1 2 2 3 3 4 # 输出索引为0-3的值(基于索引) t ...

  10. 七、linux-mysql下mysql增量备份与恢复

    1.备份的意义 运维工作:保护公司的数据     .  网站7*24小时服务 但相当来说,数据更加重要,而数据最核心的就是数据库数据,所以数据库的备份和恢复就显得十分重要. 2.备份的几个参数 mys ...