RabbitMQ使用者没有收到消息

问题描述 投票:0回答:2

我正在尝试使用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);
}

我究竟做错了什么?

java rabbitmq
2个回答
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的例子


0
投票

很确定它是因为你没有绑定队列。所以,有一个队列。并且您没有指定交换,因此您将使用默认交换。但是,当您看到带有路由密钥的消息时,您并没有告诉交换机将消息发送到哪个队列。

© www.soinside.com 2019 - 2024. All rights reserved.