简体   繁体   English

Rabbitmq,接收来自客户端的消息

[英]Rabbitmq, receive message from client

I have a simple producer and receiver classes to work with rabbitmq 我有一个简单的生产者和接收者类可以使用rabbitmq

Producer: 制片人:

public static void main(String[] argv) throws Exception {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.FANOUT);

    String message = getMessage(argv);

    channel.basicPublish(EXCHANGE_NAME, "", null, message.getBytes("UTF-8"));
    System.out.println(" [x] Sent '" + message + "'");

    channel.close();
    connection.close();
  }

And receiver : 和接收者:

public static void main(String[] argv) throws Exception {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.FANOUT);
    String queueName = channel.queueDeclare().getQueue();
    channel.queueBind(queueName, EXCHANGE_NAME, "");

    System.out.println(" [*] Waiting for messages. To exit press CTRL+C");

    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");
        System.out.println(" [x] Received '" + message + "'");
      }
    };
    channel.basicConsume(queueName, true, consumer);
  }

The question is, is it possible for Producer to know is the Receiver took the message . 问题是,生产者是否可能知道接收者是否接收了消息。 For example: 例如:

 channel.sendAndReceiveMessage(EXCHANGE_NAME, "", null, message.getBytes("UTF-8"));
        System.out.println(" [x] Sent '" + message + "'");

Short answser: You don't have a direct way to let the producer know that the consumer acked the message Long one: The second parameter you're sending here: channel.basicConsume(queueName, true, consumer); 简短回答:您没有直接的方法让生产者知道消费者已确认消息。长一个:您要在此处发送的第二个参数:channel.basicConsume(queueName,true,Consumer); is the auto-ack, setting it to false will force you to do a channel.basicAck(deliveryTag, false); 是自动确认,将其设置为false将迫使您执行channel.basicAck(deliveryTag,false); to acknowledge receipt of the message (you can get the delivery tag from the envelope) or a Channel.basicNack to tell that something failed What does it mean? 确认已收到消息(您可以从信封中获得传递标签),还是通过Channel.basicNack来告知失败,这是什么意思? it means that if you don't ack the message, it'll return to the queue and wait to be consumed again, this way, you can ensure that all messages will be consumed. 这意味着,如果您不确认消息,它将返回队列并等待再次被使用,这样,您可以确保所有消息都将被使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM