<dependency> <groupId>com.rabbitmq</groupId> <artifactId>amqp-client</artifactId> <version>5.15.0</version> </dependency>
//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();
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)