编写消费者:
package rabbit; import java.io.IOException; import java.util.concurrent.TimeoutException; import com.rabbitmq.client.*; /** * @author finley */ public class RabbitConsumer { public static void main(String[] args) throws IOException, TimeoutException { ConnectionFactory factory = new ConnectionFactory(); factory.setUsername("guest"); factory.setPassword("guest"); factory.setHost("localhost"); try (Connection conn = factory.newConnection(); Channel channel = conn.createChannel()) { String exchangeName = "test-exchange"; channel.exchangeDeclare(exchangeName, "direct", true); String queueName = channel.queueDeclare().getQueue(); String bindingKey = "hello"; channel.queueBind(queueName, exchangeName, bindingKey); while(true) { channel.basicConsume(queueName, false, "", new DefaultConsumer(channel) { @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { String routingKey = envelope.getRoutingKey(); String contentType = properties.getContentType(); String bodyStr = new String(body, "UTF-8"); System.out.println("routingKey: " + routingKey + ", contentType: " + contentType + ", body: " + bodyStr); long deliveryTag = envelope.getDeliveryTag(); channel.basicAck(deliveryTag, false); } }); } } } }RabbitMQ 的消息为字节, 可以将 Java 对象序列化后作为消息体发送。