RabbbitMQ客户端发布消息

2022/7/26 23:26:11

本文主要是介绍RabbbitMQ客户端发布消息,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

1、客户端lib

 <dependency>
   <groupId>com.rabbitmq</groupId>
   <artifactId>amqp-client</artifactId>
   <version>5.15.0</version>
</dependency>

2、获取连接和信道

//1、设置连接工厂
ConnectionFactory factory = new ConnectionFactory();
factory.setUsername("root");
factory.setPassword("root@123456");
factory.setHost("1127.0.0.1");
factory.setPort(5672);
factory.setVirtualHost("/");
//2、创建连接
Connection connection = factory.newConnection();
//3、获取通道
Channel channel = connection.createChannel();

3、发布消息并关闭连接和通道

String exchangeName = "test_ack_exchange";
String routingKey = "ack.save";

for (int i = 0; i < 5; i++) {
    Map<String, Object> headers = new HashMap<>();
    headers.put("num", i);
    AMQP.BasicProperties properties = new AMQP.BasicProperties().builder()
        .deliveryMode(2)
        .contentEncoding("UTF-8")
        .headers(headers)
        .build();
    String msg = "Hello RabbitMQ ACK Message " + i;
    channel.basicPublish(exchangeName,routingKey, true, properties, msg.getBytes(StandardCharsets.UTF_8));
}
channel.close();
connection.close();

https://www.rabbitmq.com/api-guide.html#publishinghttps://www.rabbitmq.com/api-guide.html#publishing)



这篇关于RabbbitMQ客户端发布消息的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程