我正在尝试使用RabbitMQ消息传递。消息从生产者发送到队列,但消费者未收到。我检查了服务器,它运行正常。
生产者发送者
//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();
}
消费者接收者
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);
}
我究竟做错了什么?
该代码基于一些示例?因为它与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上的示例
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句