RabbitMQ 使用事务发送和接收消息
依赖
<dependency>
<groupId>com.rabbitmq</groupId>
<artifactId>amqp-client</artifactId>
<version>5.13.0</version>
</dependency>
public class MyRabbitFactory {
public static Connection getConnection() throws IOException, TimeoutException {
// 创建连接
ConnectionFactory connectionFactory = new ConnectionFactory();
// 设置连接地址
connectionFactory.setHost("127.0.0.1");
// 设置端口号:
connectionFactory.setPort(5672);
// 设置账号和密码
connectionFactory.setUsername("guest");
connectionFactory.setPassword("guest");
// 设置VirtualHost
connectionFactory.setVirtualHost("myvh");
// 创建连接
Connection connection = connectionFactory.newConnection();
return connection;
}
}
发送消息
public void sendMessageByTransactioon() throws Exception {
Connection connection = MyRabbitFactory.getConnection();
// 设置通道
Channel channel = connection.createChannel();
// 设置消息
String msg = UUID.randomUUID().toString().substring(0, 6);
//开启事务
channel.txSelect();
//发送消息
channel.basicPublish("", "myqueue", null, msg.getBytes());
//提交
channel.txCommit();
//回滚
//channel.txRollback();
channel.close();
connection.close();
}
接收消息
public void receiveMessage() throws Exception {
Connection connection = MyRabbitFactory.getConnection();
// 设置通道
Channel channel = connection.createChannel();
//实现非公平消费,设置QPS
channel.basicQos(3);
DefaultConsumer defaultConsumer = new DefaultConsumer(channel) {
@Override
public void handleDelivery(String consumerTag, Envelope envelope
, AMQP.BasicProperties properties, byte[] body) throws IOException {
String msg = new String(body, "UTF-8");
System.out.println(msg);
//确认消息
channel.basicAck(envelope.getDeliveryTag(),false);
}
};
// 监听队列;myqueue -- 队列Name;false - 手动确认
channel.basicConsume("myqueue", false, defaultConsumer);
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现