使用代码生成队列与交换机以及使用
使用代码生成队列与交换机以及使用
一、使用配置类
1.在配置类中使用两种方式创建队列,注意Queue的包
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.QueueBuilder;
@Bean
public Queue topicQueue1() {
return new Queue("topic1.queue");
}
@Bean
public Queue topicQueue2() {
return QueueBuilder.durable("topic2.queue").build();
}
2.在配置类中创建交换机
@Bean
public TopicExchange topicExchange() {
return ExchangeBuilder.topicExchange("topic.exchange").build();
}
3.在配置类中交换机与队列进行绑定,绑定多个路由键时,需要写多个方法,而不是在后面接with或在with里写多个参数。
@Bean
public Binding topicQueue1ToTopicExchange(Queue topicQueue1, TopicExchange topicExchange) {
return BindingBuilder.bind(topicQueue1).to(topicExchange).with("#.debu");
}
二、使用注解
在监听上添加注解内容,相比之前的@RabbitListener(queues = "simple.queue")来说,复杂很多
@RabbitListener(bindings = {
@QueueBinding(
value = @Queue(name = "topic1.queue"),
exchange = @Exchange(name = "topic.exchange", type = ExchangeTypes.TOPIC),
key = "#.debu"
)
})
public void getTopicMessage1(String msg) {
log.info("消费者1号 收到消息:{}", msg);
}
三、使用
消息生产者
@Autowired
private AmqpTemplate amqpTemplate;
//or
@Autowired
private RabbitTemplate rabbitTemplate;
@Test
public void sendDirectMessage1() {
String directExchange = "direct.exchange";
amqpTemplate.convertAndSend(directExchange, "red", "颜色为red");
amqpTemplate.convertAndSend(directExchange, "blue", "颜色为blue");
amqpTemplate.convertAndSend(directExchange, "yellow", "颜色为yellow");
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· winform 绘制太阳,地球,月球 运作规律
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人