2015-12-11 237 views
0

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

我在做什麼錯?

回答

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

謝謝!我解決了這個問題。 –

0

肯定它,因爲你沒有在隊列中的結合是基於實例。所以,有一個隊列。而且你不指定交易所,所以你會使用默認的交易所。但是,當您使用路由密鑰查看消息時,您並未告知交換機將哪個隊列發送給該消息。