如何使用RabbitMQ Java从每个客户端发送/接收消息

时间:2018-06-17 16:52:59

标签: java rabbitmq broadcast

如何使用RabbitMQ在Java上实现以下情况:

sharing messagges every node

在哪里节点,向所有其他节点发送消息,每个节点从所有其他节点接收消息?

更新1: 我尝试使用以下代码创建上述情况:

ReceiveLogs.java

public class ReciveLogs {

...

    public void start() throws IOException, TimeoutException, InterruptedException {

        connection = factory.newConnection();

        channel = connection.createChannel();
        channel.queueDeclare(coda, false, false, false, null);
        channel.exchangeDeclare(exName, BuiltinExchangeType.FANOUT);
        channel.queueBind(coda, exName, "");
        channel.basicPublish(exName, codaX, null, message.getBytes("UTF-8"));

        System.out.println(" ReceiveLogs Sent: " + message);

        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(" ReceiveLogs RECEIVED:" + message);
            }
        };
        channel.basicConsume(codaX, true, consumer);
    }

}

EmitLog.java

public class EmitLog {

...

    public void start() throws IOException, TimeoutException {

        connection = factory.newConnection();
        channel = connection.createChannel();
        channel.exchangeDeclare(exName, BuiltinExchangeType.FANOUT);
        channel.queueDeclare(codaX, false, false, false, null);
        channel.queueBind(codaX, exName, "");

        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(" ROUTER Received: '" + message);
            }
        };
        String message = channel.basicConsume(codaX, true, consumer);

        channel.basicPublish(exName, "", null, message.getBytes("UTF-8"));
        System.out.println("ROUTER Sent: " + message);

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

    }
}

1 个答案:

答案 0 :(得分:0)

你可以通过创建一个"扇出"来实现这一目标。交换。

这是您需要做的设置:

  1. 创建一个粉丝交换
  2. 创建3个队列,每个节点一个队列。假设Q1,Q2和Q3对应于C1,C2和C3。
  3. 将所有队列(Q1,Q2和Q3)绑定到步骤1中创建的fanount交换
  4. 听力代码:

    1. 为每个节点创建一个侦听器。例如,C1节点侦听队列" Q1"上的消息,C2" Q2"等等。
    2. 出版: - 每当您想要发送消息时,请在您创建的广播交换中发布消息。

      这里有一个小警告:如果C1发布消息,那么C1也会收到相同的消息。因此,如果您没有任何节点处理它发布的相同消息,那么您可以使用消息中的某个属性对其进行过滤。

      进一步的文件: https://www.rabbitmq.com/tutorials/amqp-concepts.html#exchange-fanout