使用 ActiveMQ 示例
使用 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 发送 代码:
- public static void main(String[] args) throws Exception {
- ConnectionFactory connectionFactory = new ActiveMQConnectionFactory();
- Connection connection = connectionFactory.createConnection();
- connection.start();
- Session session = connection.createSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);
- Destination destination = session.createQueue("my-queue");
- MessageProducer producer = session.createProducer(destination);
- ; i<3; i++) {
- MapMessage message = session.createMapMessage();
- message.setLong("count", new Date().getTime());
- );
- //通过消息生产者发出消息
- producer.send(message);
- }
- session.commit();
- session.close();
- connection.close();
- }
Jms 接收代码:
- public static void main(String[] args) throws Exception {
- ConnectionFactory connectionFactory = new ActiveMQConnectionFactory();
- Connection connection = connectionFactory.createConnection();
- connection.start();
- final Session session = connection.createSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);
- Destination destination = session.createQueue("my-queue");
- MessageConsumer consumer = session.createConsumer(destination);
- /*//listener 方式
- consumer.setMessageListener(new MessageListener() {
- public void onMessage(Message msg) {
- MapMessage message = (MapMessage) msg;
- //TODO something....
- System.out.println("收到消息:" + new Date(message.getLong("count")));
- session.commit();
- }
- });
- Thread.sleep(30000);
- */
- ;
- ) {
- i++;
- MapMessage message = (MapMessage) consumer.receive();
- session.commit();
- //TODO something....
- System.out.println("收到消息:" + new Date(message.getLong("count")));
- }
- session.close();
- connection.close();
- }
启动 JmsReceiver 和 JmsSender 可以在看输出三条时间信息。当然 Jms 还指定有其它格式的数据,如 TextMessage
结合 Spring 的 JmsTemplate 方便用:
xml:
- <?xml version="1.0" encoding="UTF-8"?>
- <beans xmlns="http://www.springframework.org/schema/beans" 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-2.5.xsd">
- <!-- 在非 web / ejb 容器中使用 pool 时,要手动 stop,spring 不会为你执行 destroy-method 的方法
- <bean id="jmsFactory" 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="jmsFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
- <property name="brokerURL" value="tcp://localhost:61616" />
- </bean>
- <bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
- <property name="connectionFactory" ref="jmsFactory" />
- <property name="defaultDestination" ref="destination" />
- <property name="messageConverter">
- <bean class="org.springframework.jms.support.converter.SimpleMessageConverter" />
- </property>
- </bean>
- <bean id="destination" class="org.apache.activemq.command.ActiveMQQueue">
- <constructor-arg index="0" value="my-queue" />
- </bean>
- </beans>
sender:
- public static void main(String[] args) {
- ApplicationContext ctx = new FileSystemXmlApplicationContext("classpath:app*.xml");
- JmsTemplate jmsTemplate = (JmsTemplate) ctx.getBean("jmsTemplate");
- jmsTemplate.send(new MessageCreator() {
- public Message createMessage(Session session) throws JMSException {
- MapMessage mm = session.createMapMessage();
- mm.setLong("count", new Date().getTime());
- return mm;
- }
- });
- }
receiver:
- public static void main(String[] args) {
- ApplicationContext ctx = new FileSystemXmlApplicationContext("classpath:app*.xml");
- JmsTemplate jmsTemplate = (JmsTemplate) ctx.getBean("jmsTemplate");
- while(true) {
- Map<String, Object> mm = (Map<String, Object>) jmsTemplate.receiveAndConvert();
- System.out.println("收到消息:" + new Date((Long)mm.get("count")));
- }
- }
注意:直接用 Jms 接口时接收了消息后要提交一下,否则下次启动接收者时还可以收到旧数据。有了 JmsTemplate 就不用自己提交 session.commit() 了。如果使用了 PooledConnectionFactory 要把 apache-activemq-5.3.0\lib\optional\activemq-pool-5.3.0.jar 加到 classpath
参考资料:
使用 ActiveMQ 示例的更多相关文章
- Java ActiveMQ 示例
所需引入Jar包: jms-1.1.jar activemq-all-5.15.0.jar 生产者 package com.mousewheel.demo; import javax.jms.Conn ...
- 分布式-信息方式-ActiveMQ示例
实战 代码如下: 信息生产者 package test.mq.helloword; import javax.jms.Connection; import javax.jms.ConnectionFa ...
- C#---初学ActiveMQ中间件
本篇文章只适合跟我一样的初学者,因为现阶段的我们只想者怎么实现功能,不太会去考虑潜在异常.从上周开始优化公司的调控系统,原先采取的都是通过操作数据库去实现功能,客户体验效果不佳,经过领导决定是用中间件 ...
- 消息队列之 ActiveMQ(山东数漫江湖)
简介 ActiveMQ 特点 ActiveMQ 是由 Apache 出品的一款开源消息中间件,旨在为应用程序提供高效.可扩展.稳定.安全的企业级消息通信. 它的设计目标是提供标准的.面向消息的.多语言 ...
- 消息队列之 ActiveMQ
简介 ActiveMQ 特点 ActiveMQ 是由 Apache 出品的一款开源消息中间件,旨在为应用程序提供高效.可扩展.稳定.安全的企业级消息通信. 它的设计目标是提供标准的.面向消息的.多语言 ...
- 分布式--ActiveMQ 消息中间件(一) https://www.jianshu.com/p/8b9bfe865e38
1. ActiveMQ 1). ActiveMQ ActiveMQ是Apache所提供的一个开源的消息系统,完全采用Java来实现,因此,它能很好地支持J2EE提出的JMS(Java Message ...
- Active MQ C#实现
原文链接: Active MQ C#实现 内容概要 主要以源码的形式介绍如何用C#实现同Active MQ 的通讯.本文假设你已经正确安装JDK1.6.x,了解Active MQ并有一定的编程基础. ...
- ActiveMQ笔记(1):编译、安装、示例代码
一.编译 虽然ActiveMQ提供了发布版本,但是建议同学们自己下载源代码编译,以后万一有坑,还可以尝试自己改改源码. 1.1 https://github.com/apache/activemq/r ...
- ActiveMQ入门示例
1.ActiveMQ下载地址 http://activemq.apache.org/download.html 2.ActiveMQ安装,下载解压之后如下目录
随机推荐
- 阿里云ECSLinux系统下挂载磁盘
最近公司服务器老是提示磁盘空间不足,原因是以前的业务负责人开了Tomcat的debug日志并且没有做日志轮询,所以日志量非常大.当我做了日志切割轮询后发现磁盘还是太小才40G,按理外网服务器怎么可能这 ...
- PAT Basic 1020 ⽉饼 (25) [贪⼼算法]
题目 ⽉饼是中国⼈在中秋佳节时吃的⼀种传统⻝品,不同地区有许多不同⻛味的⽉饼.现给定所有种类⽉饼的库存量.总售价.以及市场的最⼤需求量,请你计算可以获得的最⼤收益是多少. 注意:销售时允许取出⼀部分库 ...
- Mysql分析排序和锁阅读总结
对于 MySQL 数据库而言,数据是存储在文件里的,而为了能够快速定位到某张表里的某条记录进行查询和修改,我们需要将这些数据以一定的数据结构进行存储,这个数据结构就是我们说的索引.能够支持快速查找的数 ...
- 微信小程序-wx.request-路由跳转-数据存储-登录与授权
wx.request 相当于发送ajax请求 官方文档示例代码 wx.request({ url: 'test.php', //仅为示例,并非真实的接口地址 data: { x: '', y: '' ...
- JavaSE--数字签名之校验签名
参考:http://blog.csdn.net/dotuian/article/details/51722300 关于keystore的简单介绍 Keytool是一个Java数据证书的管理工具 ,Ke ...
- 小白学习之pytorch框架(3)-模型训练三要素+torch.nn.Linear()
模型训练的三要素:数据处理.损失函数.优化算法 数据处理(模块torch.utils.data) 从线性回归的的简洁实现-初始化模型参数(模块torch.nn.init)开始 from torc ...
- \_\_setitem\_\_和\_\_getitem和\_\_delitem__
目录 __setitem__和__getitem和__delitem__ 一.__setitem__ 二.__getitem__ 三.__delitem__与__delattr__ 四.总结 __se ...
- 如何把Visual Studio完全安装在其他磁盘
//Visual Studio快把我c盘吃完了,就网上找了找解决方法,自己总结一下,方便理解 第一步 找到以下文件夹 C:\\Program Files (x86)\\Microsoft SDKs C ...
- xls文件转化txt
xls文件转化txt # -*- coding:utf-8 -*- # 安装pywin32包 http://sourceforge.net/projects/pywin32/files/pywin32 ...
- Linux系统国内镜像站点
一,更换说明 第一步 备份 如centos, mv /etc/yum.repos.d/CentOS-Base.repo /etc/yum.repos.d/CentOS-Base.repo.backup ...