packagecom.xdclass.simple;import com.rabbitmq.client.*;importjava.io.IOException;public classRecv {private final static String QUEUE_NAME = "hello";public static void main(String[] argv) throwsException {
ConnectionFactory factory= newConnectionFactory();
factory.setHost("192.168.216.130");
factory.setUsername("admin");
factory.setPassword("password");
factory.setVirtualHost("/dev");
factory.setPort(5672);//消费者⼀般不增加⾃动关闭
Connection connection =factory.newConnection();
Channel channel=connection.createChannel();
channel.queueDeclare(QUEUE_NAME,false, false, false, null);
System.out.println(" [*] Waiting for messages.To exit press CTRL + C");//回调方法,下⾯两种都⾏
Consumer consumer = newDefaultConsumer(channel) {
@Overridepublic voidhandleDelivery(String consumerTag, Envelope envelope,
AMQP.BasicProperties properties,byte[] body) throwsIOException {//consumerTag 是固定的 可以做此会话的名字,deliveryTag 每次接收消息 +1
System.out.println("consumerTag 消息标识 = " +consumerTag);//可以获取交换机,路由健等System.out.println("envelope元数据 = "+envelope);
System.out.println("properties配置信息 = " +properties);
System.out.println("body=" + new String(body, "utf-8"));
}
};
channel.basicConsume(QUEUE_NAME,true, consumer);//也可以用下面这种
/*DeliverCallback deliverCallback = (consumerTag, delivery) -> {
String message = new String(delivery.getBody(), "UTF-8");
System.out.println(" [x] Received '" + message + "'");
};
//⾃动确认消息
channel.basicConsume(QUEUE_NAME, true, deliverCallback, consumerTag -> {
});*/}
}