用于测试RabbitMQ消费者和生产者的JUnit测试

时间:2018-06-09 20:39:21

标签: java junit rabbitmq

我想创建JUnit测试来测试RabbitMQ生产者和消费者。我试过这个:

public class QueueConsumer extends TestCase {

    private static final String EXCHANGE_NAME = "logs";

    public static void Producer(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 = "some test message";

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

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


    public static void Consumer(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, BasicProperties properties, byte[] body)
                    throws IOException {
                String message = new String(body, "UTF-8");
                System.out.println(" [x] Received '" + message + "'");
            }
        };
        channel.basicConsume(queueName, true, consumer);
    }

}

如何在不同的线程中运行Consumer和Producer以便在它们之间交换消息?

例如,Consumer线程向Producer发送10条消息?我只得到这个结果。没有消息传递。

[x] Sent 'some test message'
 [*] Waiting for messages. To exit press CTRL+C

0 个答案:

没有答案