import com.rabbitmq.client.*; import java.io.IOException; /** * 消费消息,手动确认消息,autoAck 设置为 false * @author hxstrive.com * @date 2022年2月17日13:59:29 */ public class ConsumerMessage2 { private static final String EXCHANGE_NAME = "exchange_" + ConsumerMessage2.class.getSimpleName(); /** * 发送消息 */ private void sender() throws Exception { // 创建连接 ConnectionFactory factory = new ConnectionFactory(); factory.setHost("127.0.0.1"); factory.setPort(5672); Connection connection = factory.newConnection(); // 创建通道 Channel channel = connection.createChannel(); channel.exchangeDeclare(EXCHANGE_NAME, "topic"); // 发送消息 System.out.println("[Send] Sending Message..."); byte[] msg = "hello wrold".getBytes(); channel.basicPublish(EXCHANGE_NAME, "www.hxstrive.com", null, msg); // 释放资源 channel.close(); connection.close(); } /** * 消费消息 */ private void consumer() throws Exception { // 创建连接 ConnectionFactory factory = new ConnectionFactory(); factory.setHost("127.0.0.1"); factory.setPort(5672); Connection connection = factory.newConnection(); // 创建通道 final Channel channel = connection.createChannel(); channel.exchangeDeclare(EXCHANGE_NAME, "topic"); // 绑定exchange与queue String queueName = channel.queueDeclare().getQueue(); channel.queueBind(queueName, EXCHANGE_NAME, "*.hxstrive.com"); System.out.println("[Receive] Waiting Message..."); // 消费消息 channel.basicConsume(queueName, false, new DefaultConsumer(channel){ @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { System.out.println("[Receive] Receive Message :: " + new String(body)); System.out.println("routingKey = " + envelope.getRoutingKey()); System.out.println("contentType = " + properties.getContentType()); // 手动确认消息 long deliveryTag = envelope.getDeliveryTag(); channel.basicAck(deliveryTag, false); } }); } public static void main(String[] args) throws Exception { ConsumerMessage2 demo = new ConsumerMessage2(); demo.consumer(); demo.sender(); } }