1. direct 交换机
(1)导入依赖:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-amqp</artifactId> </dependency>
(2)application.yaml
spring: rabbitmq: host: localhost port: 5672 username: guest password: guest
(3)RabbitDirectConfig : 创建direct 交换机 + 创建队列 + 绑定
/** * 高级消息队列协议 amqp */ @Configuration public class RabbitDirectConfig { //1. 创建direct交换机 @Bean public DirectExchange newExchange(){ return new DirectExchange("myExchange",true,false); } //2. 创建队列 @Bean public Queue newQueue(){ return new Queue("myQueue",true); } //3. 绑定 @Bean public Binding bind(){ return BindingBuilder.bind(newQueue()).to(newExchange()).with("myKey"); } }
(4)生产者
@RestController public class DirectProducer { @Autowired private RabbitTemplate rabbitTemplate; @PostMapping("direct") public String sendMessage(String message){ rabbitTemplate.convertAndSend("myExchange","myKey",message); return "send message successfully"; } }
(5)消费者
@Component public class DirectConsumer { // 监听并接收队列中的消息 @RabbitHandler @RabbitListener(queues = "myQueue") public void getMessage(String message){ System.out.println("消费者接收到了消息:" + message); } }