activemq学习笔记2
基本步骤:#
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)的参数二
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挂了,消息不会丢失
<persistenceAdapter>
<kahaDB directory="${activemq.data}/kahadb"/>
</persistenceAdapter>
配置持久化:
producer.setDeliveryMode(DeliveryMode.PERSISTENT);
public interface DeliveryMode {
int NON_PERSISTENT = 1;
int PERSISTENT = 2;
}
异步#
发送消息#
ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("tcp://127.0.0.1:61616");
factory.setUseAsyncSend(true);
非持久化消息模式下,默认就是异步发送过程,如果需要对非持久化消息的每次发送的消息都获得broker的回执的话
connectionFactory.setAlwaysSyncSend()
接受消息#
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()
分类:
03 MQ
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 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)