我正在嘗試使用RabbitMQ消息。消息從生產者發送到隊列,但消費者沒有收到它。我檢查了服務器,它運行正常。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);
}
我在做什麼錯?
謝謝!我解決了這個問題。 –