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();
}
}
If you're using the following dependency in your project...
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
...then you can leverage the AmqpAdmin
Bean that's provided by the Spring Boot AutoConfiguration within your Tests.
Example:
@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);
}
}
The example above shows how you can get the message count for a particular queue.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With