我正在尝试使用RabbitMQ消息传递。消息从生产者发送到队列,但消费者不接收它。我检查了服务器,它运行正常。
ProducerSender
//the messageToSend is set in another class.
private static final String TASK_QUEUE_NAME = "hello";
public void writeMessage(Message messageToSend) throws IOException, TimeoutException {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
channel.queueDeclare(TASK_QUEUE_NAME, true, false, false, null);
String message = messageToSend.getTitle()+" "+messageToSend.getYear()+" "+messageToSend.getPrice();
channel.basicPublish("", TASK_QUEUE_NAME, null,
message.getBytes());
channel.close();
connection.close();
}
ConsumerReceiver
public void readMessage() throws IOException, TimeoutException {
Socket clientSocket = new Socket(host, port);
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
channel.queueDeclare(TASK_QUEUE_NAME, true, false, false, null);
Consumer consumer = new DefaultConsumer(channel) {
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body)
throws IOException {
String message = new String(body, "UTF-8"); //message is null
System.out.println(" [x] Received '" + message + "'");
}
};
channel.basicConsume(TASK_QUEUE_NAME, true, consumer);
}
我做错了什么?
答案 0 :(得分:1)
此代码基于一些示例?因为它与RabbitMQ Java指南中显示的表单不同。 我会按照我使用的方式发给你,也许你可以想出它里面缺少的东西。
QueueingConsumer.Delivery queueMessage = consumer.nextDelivery();
String message = new String(queueMessage.getBody());
// if auto-ack is not set
channel.basicAck(queueMessage.getEnvelope().getDeliveryTag(), false);
这是基于https://www.rabbitmq.com/tutorials/tutorial-two-java.html
的示例答案 1 :(得分:0)
非常确定,因为你没有绑定队列。所以,有一个队列。并且您没有指定交换,因此您将使用默认交换。但是,当您看到带有路由密钥的消息时,您并没有告诉交换机将消息发送到哪个队列。