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)

posted @ 2022-07-26 14:27  往事随雨  阅读(126)  评论(0)    收藏  举报