autoStartup
必须要设为 true
,否则Spring容器不会加载RabbitAdmin类 RabbitAdmin
底层实现就是从 Spring
容器中获取 Exchange
, Binding
, RoutingKey
以及 Queue
的 @Bean
申明 package com.wyg.rabbitmq.springamqp; import org.springframework.amqp.rabbit.connection.CachingConnectionFactory; import org.springframework.amqp.rabbit.connection.ConnectionFactory; import org.springframework.amqp.rabbit.core.RabbitAdmin; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * RabbitAdmin * * @author wyg0405@gmail.com * @date 2019-11-25 15:11 * @since JDK1.8 * @version V1.0 */ @Configuration public class RabbitConfig { @Bean public ConnectionFactory connectionFactory() { CachingConnectionFactory cachingConnectionFactory = new CachingConnectionFactory(); cachingConnectionFactory.setAddresses("localhost:5672"); cachingConnectionFactory.setUsername("guest"); cachingConnectionFactory.setPassword("guest"); cachingConnectionFactory.setVirtualHost("/"); return cachingConnectionFactory; } @Bean public RabbitAdmin rabbitAdmin(ConnectionFactory connectionFactory) { RabbitAdmin rabbitAdmin = new RabbitAdmin(connectionFactory); /* * autoStartup 必须要设为 true ,否则Spring容器不会加载RabbitAdmin类 */ rabbitAdmin.setAutoStartup(true); return rabbitAdmin; } }
package com.wyg.rabbitmq.springamqp; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.amqp.core.*; import org.springframework.amqp.rabbit.core.RabbitAdmin; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest public class RabbitConfigTest { @Autowired RabbitAdmin rabbitAdmin; @Test public void testRabbitAdmin() { // 申明一个direct Exchange rabbitAdmin.declareExchange(new DirectExchange("testRabbitAdmin.exchage.direct", false, false)); // 申明一个fanout Exchange rabbitAdmin.declareExchange(new FanoutExchange("testRabbitAdmin.exchage.fanout", false, false)); // 申明一个topic Exchange rabbitAdmin.declareExchange(new TopicExchange("testRabbitAdmin.exchange.topic", false, false)); // 申明 name 一个queue rabbitAdmin.declareQueue(new Queue("testRabbitAdmin.queue.direct", false, false, false)); // 申明 name 一个queue rabbitAdmin.declareQueue(new Queue("testRabbitAdmin.queue.fanout", false, false, false)); // 申明 name 一个queue rabbitAdmin.declareQueue(new Queue("testRabbitAdmin.queue.topic", false, false, false)); // 绑定 rabbitAdmin.declareBinding(new Binding("testRabbitAdmin.queue.direct", Binding.DestinationType.QUEUE, "testRabbitAdmin.exchage.direct", "direct.abc", null)); // 使用BindingBuilder绑定 rabbitAdmin.declareBinding(BindingBuilder.bind(new Queue("testRabbitAdmin.queue.topic", false, false, false)) .to(new TopicExchange("testRabbitAdmin.exchange.topic", false, false)).with("topicKey.#")); // 清空队列,先手工插入一条数据到testRabbitAdmin.queue.fanout rabbitAdmin.purgeQueue("testRabbitAdmin.queue.fanout", true); } }
测试结果