- 配置文件和核心依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
spring:
rabbitmq:
username: guest
password: guest
virtual-host: /
addresses: 192.168.3.8:5672
- 声明交换机队列和绑定
package com.vivo.demo2.springamqp;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class RabbtimqConfig {
@Bean("topicQueue")
public Queue queue() {
return new Queue("topic.queue", false, false, false);
}
@Bean("topicExchange")
public Exchange exchange() {
return new TopicExchange("topic.exchange", false, false);
}
@Bean
public Binding topicQueueBindingTopicExchange(Queue topicQueue,Exchange topicExchange) {
return BindingBuilder.bind(topicQueue).to(topicExchange).with("topic.#").noargs();
}
}
- 使用(使用junit做测试)
package com.vivo.demo2;
import org.junit.jupiter.api.Test;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
public class Test1 {
@Autowired
private RabbitTemplate rabbitTemplate;
@Test
public void test1(){
rabbitTemplate.convertAndSend("topic.exchange","topic.aaaa","hello 12345!!!");
}
}
- 通过mq管控台观察,我们就可以看到,已经给我们创建好了exchange和队列,并建立好了绑定关系。并且消息也能成功发送到mq了。