Mike Bowman
Mike Bowman

Reputation: 73

RabbitMQ consumer doesn't receive the message

I am trying to use RabbitMQ messaging. The message is sent to queue from producer, but the consumer doesn't receive it. I checked the server and it's running properly.

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);
}

What am I doing wrong?

Upvotes: 0

Views: 4241

Answers (2)

chris.ellis
chris.ellis

Reputation: 893

Pretty sure its because you dont have a binding on the queue. So, there is a queue. And you dont specify an exchange so you will use the default one. But you aren't telling the exchange which queue to send the message to when it sees a message with your routing key.

Upvotes: 0

catastrophic error
catastrophic error

Reputation: 390

This code was based on some example? because is different than the form shown at the RabbitMQ Java guide. I'll send you the way I use, maybe you can figure what is missing from it.

QueueingConsumer.Delivery queueMessage = consumer.nextDelivery();
String message = new String(queueMessage.getBody());
// if auto-ack is not set
channel.basicAck(queueMessage.getEnvelope().getDeliveryTag(), false);

this was based on the examples at https://www.rabbitmq.com/tutorials/tutorial-two-java.html

Upvotes: 1

Related Questions