其他分享
首页 > 其他分享> > RabbbitMQ客户端发布消息

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)

标签:String,factory,headers,发布,new,RabbbitMQ,com,channel,客户端
来源: https://www.cnblogs.com/Nilekai/p/16520870.html