使用java发送和监听rabbitMQ的多个队列

时间:2015-03-16 15:28:43

标签: java rabbitmq

我为每种消息类型提供了两种类型的队列 - 1. REQUEST_QUEUE - 用于发送消息2. RESPONSE_QUEUE - 用于获取消息响应。

因此,如果有5种消息类型,我们有10个队列。

作为客户端,我想向所有请求队列发送消息,并且需要根据相关ID监听响应队列。 用于发布我在代码下面使用的消息:

public static void publishMessage(String exchange, String routingKey, String responseKey, List<String> messageList) throws IOException, Exception {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(Constants.rabbitMQServerProperties.HOST_NAME);
    factory.setUsername(Constants.rabbitMQServerProperties.USER_NAME);
    factory.setPassword(Constants.rabbitMQServerProperties.PASSWORD);
    factory.setPort(Constants.rabbitMQServerProperties.PORT);
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();
    //System.out.println(channel.isOpen());
    //System.out.println(message);
    for(String message : messageList) {
        channel.basicPublish(exchange, routingKey, true, MessageProperties.PERSISTENT_BASIC,  message.getBytes());
    }
    channel.close();
    connection.close();
    System.out.println("Message published successfully!\n \n");
    Connection con = factory.newConnection();
    // ExecutorService threadExecutor = Executors.newFixedThreadPool(5);
    // listen to response queue
    Worker fast = new Worker(0, threadExecutor, con.createChannel(), responseKey);
}

在最后一行,一旦我发送消息,我正在收听消息队列。

Worker.java:

public class Worker extends DefaultConsumer {
    String name;
    Channel channel;
    String queue;
    int processed;
    ExecutorService executorService;

    public Worker(int prefetch, ExecutorService threadExecutor, Channel c, String q) throws Exception {
        super(c);
        channel = c;
        queue = q;
        channel.basicQos(prefetch);
        channel.basicConsume(queue, false, this);
        executorService = threadExecutor;
    }

    @Override
    public void handleDelivery(String consumerTag,
                               Envelope envelope,
                               AMQP.BasicProperties properties,
                               byte[] body) throws IOException {
        String response = new String(body);
        String routingKey = envelope.getRoutingKey();
        String contentType = properties.getContentType();
        String correlationId = properties.getCorrelationId();
        System.out.println(queue+" Response :: "+ response);

        }

    }
}

以下是我的问题:

  1. 在收听队列时,我只需要选择我提交的消息(比方说,我有与我相关的ID列表),如果不是来自我的corrleation id,那么我需要发送消息回到响应队列。我怎么能在这里做?

  2. 一旦收到所有消息,我需要关闭我的开放连接。

  3. 如果我一个接一个地向所有5个队列发送消息,我的发送方式是&amp;听是正确的吗?
  4. 提前致谢!

0 个答案:

没有答案