RabbitMQ-如何获取带有某些路由键的消息?

时间:2019-06-20 18:17:21

标签: java rabbitmq

可以使用几个不同的路由键将消息发送到队列,但是我只想获取具有“ MyRouting.Route.RtKey1”或“ MyRouting.Route.RtKey2”的消息。我将以下代码用作使用者代码,但是无论管理控制台中显示的消息具有路由键如何,都不会收到任何消息。我怎么只能得到我想要的消息?

String myMessage;
String routingKeyReceived;

private void getMessage() {
    String FROM_QUEUE_NAME = "FromQueue";
    String EXCHANGE_NAME = "amq.topic";
    myMessage = "";
    routingKeyReceived = "";

    ConnectionFactory factory = new ConnectionFactory();
    factory.setUsername("test");
    factory.setPassword("test");
    factory.setVirtualHost("MyVirtualHost");
    factory.setHost("172...");
    factory.setPort(5672);

    try 
    {
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();

        channel.exchangeDeclare(EXCHANGE_NAME, "topic", true);

        channel.queueDeclare(FROM_QUEUE_NAME, true, false, false, null);

        channel.queueBind(FROM_QUEUE_NAME, EXCHANGE_NAME, "MyRouting.Route.RtKey1");
        channel.queueBind(FROM_QUEUE_NAME, EXCHANGE_NAME, "MyRouting.Route.RtKey2");

        DeliverCallback deliverCallback = (consumerTag, delivery) -> {
            myMessage = new String(delivery.getBody(), "UTF-8");
            routingKeyReceived = delivery.getEnvelope().getRoutingKey();
        };
        channel.basicConsume(FROM_QUEUE_NAME, true, deliverCallback, consumerTag -> { });

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

    } catch (Exception e) {
    }
}

0 个答案:

没有答案