I am trying to get a count of the number of messages on my rabbit queue and then purge the queue in my test. Looking around it seems to suggest I need to use RabbitAdmin to get the counts but unsure how to autowire this into my test? any ideas?
@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;
}
test class:
@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();
}
}