Spring boot rabbitmq队列计数?

时间:2017-08-18 20:40:37

标签: spring-boot rabbitmq

我正在尝试计算我的兔子队列中的消息数量,然后在我的测试中清除队列。看看它似乎表明我需要使用RabbitAdmin来获取计数,但不确定如何将其自动装入我的测试中?任何想法?

@Configuration
public class MyConfig {

@Value("${queue.producer.name}")
private String queueName;


@Bean
public Jackson2JsonMessageConverter jsonMessageConverter(){
    Jackson2JsonMessageConverter con= new Jackson2JsonMessageConverter();
    return con;
}

@Autowired
private ConnectionFactory rabbitConnectionFactory;

@Bean
public Queue queue() {
    return new Queue(queueName, true);
}

@Bean
public RabbitTemplate rabbitTemplate() {
    RabbitTemplate r = new RabbitTemplate(rabbitConnectionFactory);
    r.setMessageConverter(jsonMessageConverter());
    r.setConnectionFactory(rabbitConnectionFactory);
    return r;
}

测试类:

 @RunWith(SpringRunner.class)
@SpringBootTest
public class TestIT {


@Resource
private RabbitAdmin admin;

@Test
public void testQueue() throws IOException, InterruptedException{

    System.out.println(getQueueCount("publish"));

    admin.purgeQueue("publish",true);


}

protected int getQueueCount(final String name) {
    AMQP.Queue.DeclareOk declareOk = admin.getRabbitTemplate().execute(new ChannelCallback<AMQP.Queue.DeclareOk>() {
        public AMQP.Queue.DeclareOk doInRabbit(Channel channel) throws Exception {
            return channel.queueDeclarePassive(name);
        }
    });
    return declareOk.getMessageCount();
}

}

1 个答案:

答案 0 :(得分:1)

如果您在项目中使用以下依赖项...

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-amqp</artifactId>
</dependency>

...然后您可以利用测试中Spring Boot AutoConfiguration提供的AmqpAdmin Bean。

示例:

@RunWith(SpringRunner.class)
@SpringBootTest
public class RabbitmqTests {

    @Autowired
    private AmqpAdmin amqpAdmin;

    @Test
    public void purgeQueue() throws Exception {
        Integer count = (Integer) amqpAdmin.getQueueProperties("publish").get("QUEUE_MESSAGE_COUNT");
        amqpAdmin.purgeQueue("publish", true);
    }

}

上面的示例显示了如何获取特定队列的消息计数。