ActiveMQ 入门例子
来源:互联网 发布:答题赚钱软件 编辑:程序博客网 时间:2024/05/03 12:10
一:新建Maven项目,加入如下依赖
<dependency><groupId>org.apache.activemq</groupId><artifactId>activemq-all</artifactId><version>5.11.1</version></dependency>
二:
server(嵌入式,无需下载安装activemq)
package com.lala.mq;import java.util.concurrent.TimeUnit;import org.apache.activemq.broker.BrokerService;public class Server {public static void main(String[] args)throws Exception{BrokerService broker = new BrokerService();broker.addConnector("tcp://127.0.0.1:55551");broker.setUseJmx(false);broker.start();TimeUnit.SECONDS.sleep(9999);}}
Producer(生产者)
package com.lala.mq;import javax.jms.Connection;import javax.jms.ConnectionFactory;import javax.jms.MessageProducer;import javax.jms.Queue;import javax.jms.Session;import javax.jms.TextMessage;import org.apache.activemq.ActiveMQConnectionFactory;public class MyProducer{public static void main(String[] args) throws Exception{ConnectionFactory cf = new ActiveMQConnectionFactory("tcp://127.0.0.1:55551");Connection conn = cf.createConnection();conn.start();Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);Queue queue = session.createQueue("cib");MessageProducer producer = session.createProducer(queue);TextMessage tm = null;for(int i=1;i<=5;i++){tm = session.createTextMessage("this is test message and msgid = " + i);producer.send(tm);}session.close();conn.close();}}
Consumer(消费者)
package com.lala.mq;import javax.jms.Connection;import javax.jms.ConnectionFactory;import javax.jms.MessageConsumer;import javax.jms.Queue;import javax.jms.Session;import javax.jms.TextMessage;import org.apache.activemq.ActiveMQConnectionFactory;public class MyConsumer {public static void main(String[] args)throws Exception{ConnectionFactory cf = new ActiveMQConnectionFactory("tcp://127.0.0.1:55551");Connection conn = cf.createConnection();conn.start();Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);Queue queue = session.createQueue("cib");MessageConsumer consumer = session.createConsumer(queue);consumer.setMessageListener((message) -> {TextMessage tm = (TextMessage)message;try {System.out.println("收到消息:" + tm.getText());} catch (Exception e) {e.printStackTrace();}});}}
三:运行
先运行:Server
再运行:Consumer
最后运行:Producer
即可看到输出
最后
注意:以上做法不需要事先下载安装activemq服务
9 0
- ActiveMq-PTP入门例子
- ActiveMQ 入门例子
- ActiveMq-Publisher/Subscribe入门例子
- ActiveMQ入门学习小例子
- ActiveMQ例子
- ActiveMQ例子
- ActiveMQ : ActiveMQ入门介绍
- ActiveMQ入门
- ActiveMQ入门
- activemq入门
- ActiveMQ 入门
- activeMQ 入门
- ActiveMQ入门
- activeMQ入门
- activemq 入门
- ActiveMQ 入门
- ActiveMq入门
- ActiveMQ入门
- 设计模式 学习资料总结
- 棋盘问题(POJ 1321)
- 从WIN8.1升级到WIN10后,网络适配器消失无法联网
- 反片语
- 状态压缩DP入门题
- ActiveMQ 入门例子
- 【CodeVS1036】商务旅行
- TCP/IP、Http、Socket的区别
- uva 10325 容斥原理
- String、StringBuffer、StringBuilder的区别
- 指针常量和常量指针
- g++ sleep头文件
- sql面题
- C#求两圆相交点,转载自百度知道 作者lrh3321