路由模式 Direct Exchange 将消息队列queue绑定到 DirectExchange 交换机上,给定一个路由key ,生产者发送消息到交换机,消费者通过监听获取消息,开发中注意key一直,否则出现不匹配异常
rabbitmq 实现了ampq pom 用到的依赖
<!--rabbitmq-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
application.yml
spring:
rabbitmq:
host: 172.01.01.68
port: 5672
username: test
password:test
配置文件
@Configuration
public class AmqpConfig {
public static final String QUEUE = "QUEUE";
public static final String EXCHANGE = "EXCHANGE";
public static final String ROUNTING = "ROUNTING";
//注入队列
@Bean
public Queue testDirectQueue() {
//注意队列的3个参数
//durable 是否持久化 一般为开启状态
//exclusive: 是否开启当前创建连接
//autodelete: 是否自动删除
return new Queue(QUEUE, true);
}
//注入交换机
@Bean
DirectExchange TestDirectExchage() {
return new DirectExchange(EXCHANGE, true, false);
}
//队列绑定交换机 ,
Binding bindingDirect() {
return BindingBuilder.bind(testDirectQueue()).to(TestDirectExchage()).with(ROUNTING);
}
Controller 写消息 provider
@Autowirte
RabbitTemplate rabbitTemplate;
@GetMapping("/Test")
public String TestMessageAck() {
rabbitTemplate.convertAndSend("non-existent-exchange", "TestDirectRouting", "数据数据");
return "ok";
}
消息消费者 consumer
@Controller
public class DirectConsumer{
@RabbitHandler
@RabbitListener(queues =ROUNTING)
public void test(String test){
System.out.println(test);
}
}
|