在整合Spring/Springboot之前,我们加入相关的依赖在pom中:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.amqp</groupId>
<artifactId>spring-rabbit-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.rabbitmq</groupId>
<artifactId>amqp-client</artifactId>
</dependency>
</dependencies>
我们写一个配置类的bean注入进去:
@Configuration
@ComponentScan({"com.jlu.rabbitmqspring.*"})
public class RabbitMQConfig {
@Bean
public ConnectionFactory connectionFactory(){
CachingConnectionFactory factory = new CachingConnectionFactory();
factory.setHost("192.168.119.134");
factory.setUsername("king");
factory.setPassword("123456");
factory.setVirtualHost("/");
return factory;
}
@Bean
public RabbitAdmin rabbitAdmin(ConnectionFactory connectionFactory){
RabbitAdmin rabbitAdmin = new RabbitAdmin(connectionFactory);
rabbitAdmin.setAutoStartup(true);
return rabbitAdmin;
}
}
上面那些根据你自己的情况进行修改,包括主机名以及账号密码等设置。接下来,我们写一下测试类:
@SpringBootTest
class RabbitmqSpringApplicationTests {
@Autowired
private RabbitAdmin rabbitAdmin;
@Test
void contextLoads() {
rabbitAdmin.declareExchange(new DirectExchange("test.direct",false,false));
rabbitAdmin.declareExchange(new TopicExchange("test.topic",false,false));
rabbitAdmin.declareQueue(new Queue("test.direct.queue",false));
rabbitAdmin.declareQueue(new Queue("test.topic.queue",false));
rabbitAdmin.declareBinding(new Binding("test.direct.queue",
Binding.DestinationType.QUEUE,
"test.direct","direct",new HashMap<>()));
// 上面是方式一,下面是方式二
rabbitAdmin.declareBinding(BindingBuilder.bind(new Queue("test.topic.queue",false))
.to(new TopicExchange("test.topic",false,false))
.with("test.#"));
//第一步创建队列,第二步创建exchange并绑定到上面,第三步创建路由键
}
}
方式二是流式写法,方式一需要提前创建exchange和queue,方式二不需要。
来源:CSDN
作者:攻城猿bilibili
链接:https://blog.csdn.net/sinat_36899414/article/details/104074360