1、创建SpringBoot工程,添加RabbitMQ依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
?2、编写工程配置
spring.application.name=springboot_rabbitmq
#我使用的是我电脑本地的RabbitMQ配置,所以是127.0.0.1
spring.rabbitmq.host=127.0.0.1
spring.rabbitmq.virtual-host=/
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest
spring.rabbitmq.port=5672
3、编写RabbitMqConfig配置类
@Configuration
public class RabbitMqConfig {
//初始化队列名称
@Bean
public Queue myQueue() {
return new Queue("myqueue");
}
//声明交换器
@Bean
public Exchange myExchange() {
return new DirectExchange("myExchange", false, false, null);
}
//绑定关系
@Bean
public Binding myBinding() {
return new Binding("myqueue", Binding.DestinationType.QUEUE, "myExchange", "direct.biz.ex", null);
}
}
4、编写接口
@RestController
public class TestController {
@Autowired
private AmqpTemplate amqpTemplate;
@RequestMapping("/send/{msg}")
public String sendMsg(@PathVariable("msg")String msg){
amqpTemplate.convertAndSend("myExchange","direct.biz.ex",msg);
return "OK";
}
}
5、编写消费者监听类,用来获取并消费接口传过来的msg
@Component
public class TestConsumer {
@RabbitListener(queues = "myqueue")
public void consumerQueue(String msg) {
System.out.println("消费的内容是:" + msg);
}
}
6、运行并请求接口
http://localhost:8080/send/helloRabbit
7、控制台打印
消费的内容是:helloRabbit