activemq学习笔记2

基本步骤:#

Copy
ConnectionFactory factory = new ActiveMQConnectionFactory("tcp://127.0.0.1:61616"); Connection connection = factory.createConnection(); connection.start(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); Destination que = new ActiveMQQueue("que"); MessageProducer producer = session.createProducer(que); TextMessage msg = session.createTextMessage("hello activemq"); producer.send(msg); //session.commit(); session.close(); connection.close();

注意的地方#

1、连接开启
connection.start();
2.1、会话类型(事务型,非事务型)
connection.createSession(false, Session.AUTO_ACKNOWLEDGE)的参数一
2.2、应答模式
connection.createSession(false, Session.AUTO_ACKNOWLEDGE)的参数二

Copy
int AUTO_ACKNOWLEDGE = 1; int CLIENT_ACKNOWLEDGE = 2; int DUPS_OK_ACKNOWLEDGE = 3; int SESSION_TRANSACTED = 0;

2.3、组合方式
false:
int AUTO_ACKNOWLEDGE = 1;
int CLIENT_ACKNOWLEDGE = 2;
int DUPS_OK_ACKNOWLEDGE = 3;
true:
int SESSION_TRANSACTED = 0;

事务型需要session.commit()
非事务型不能session.commit()

持久化#

默认是持久化的,消息保存在磁盘,所以即使mq挂了,消息不会丢失

Copy
<persistenceAdapter> <kahaDB directory="${activemq.data}/kahadb"/> </persistenceAdapter>

配置持久化:

Copy
producer.setDeliveryMode(DeliveryMode.PERSISTENT);
Copy
public interface DeliveryMode { int NON_PERSISTENT = 1; int PERSISTENT = 2; }

异步#

发送消息#

Copy
ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("tcp://127.0.0.1:61616"); factory.setUseAsyncSend(true);

非持久化消息模式下,默认就是异步发送过程,如果需要对非持久化消息的每次发送的消息都获得broker的回执的话

Copy
connectionFactory.setAlwaysSyncSend()

接受消息#

Copy
public class MsgReceiver { public static void main(String[] args) { try { ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("tcp://127.0.0.1:61616"); Connection connection = factory.createConnection(); connection.start(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); Destination que = new ActiveMQQueue("que"); MessageConsumer consumer = session.createConsumer(que); consumer.setMessageListener(new MsgListener()); //session.commit(); //session.close(); } catch (JMSException e) { e.printStackTrace(); } } } class MsgListener implements MessageListener { @Override public void onMessage(Message message) { TextMessage msg = (TextMessage) message; try { System.out.println(msg.getText()); } catch (JMSException e) { e.printStackTrace(); } } }

异步接收不能提前关闭session,非事务不能commit()

posted @   懒企鹅  阅读(172)  评论(0编辑  收藏  举报
编辑推荐:
· Linux glibc自带哈希表的用例及性能测试
· 深入理解 Mybatis 分库分表执行原理
· 如何打造一个高并发系统?
· .NET Core GC压缩(compact_phase)底层原理浅谈
· 现代计算机视觉入门之:什么是图片特征编码
阅读排行:
· 手把手教你在本地部署DeepSeek R1,搭建web-ui ,建议收藏!
· Spring AI + Ollama 实现 deepseek-r1 的API服务和调用
· 数据库服务器 SQL Server 版本升级公告
· 程序员常用高效实用工具推荐,办公效率提升利器!
· C#/.NET/.NET Core技术前沿周刊 | 第 23 期(2025年1.20-1.26)
点击右上角即可分享
微信分享提示
CONTENTS