通过Spring配置,Bean注入的形式
依赖配置
| |
| <dependency> |
| <groupId>org.springframework.boot</groupId> |
| <artifactId>spring-boot-starter-amqp</artifactId> |
| </dependency> |
yaml文件配置
| spring: |
| rabbitmq: |
| host: 127.0.0.1 |
| port: 5672 |
| virtual-host: /hmall |
| username: hmall |
| password: 123 |
| |
fanout交换机
| @Configuration |
| public class FanoutConfiguration { |
| |
| @Bean |
| public FanoutExchange fanoutExchange(){ |
| |
| return new FanoutExchange("hmall.fanout2"); |
| } |
| |
| @Bean |
| public Queue fanoutQueue3(){ |
| |
| return new Queue("fanout.queue3"); |
| } |
| |
| @Bean |
| public Binding fanoutBinding3(Queue fanoutQueue3, FanoutExchange fanoutExchange){ |
| return BindingBuilder.bind(fanoutQueue3).to(fanoutExchange); |
| } |
| |
| @Bean |
| public Queue fanoutQueue4(){ |
| return QueueBuilder.durable("fanout.queue4").build(); |
| |
| } |
| |
| @Bean |
| public Binding fanoutBinding4(){ |
| return BindingBuilder.bind(fanoutQueue4()).to(fanoutExchange()); |
| } |
| } |
direct交换机
| @Configuration |
| public class DirectConfiguration { |
| |
| @Bean |
| public DirectExchange directExchange(){ |
| |
| return new DirectExchange("hmall.direct"); |
| } |
| |
| @Bean |
| public Queue directQueue1(){ |
| |
| return new Queue("direct.queue1"); |
| } |
| |
| @Bean |
| public Binding directQueue1BindingRed(Queue directQueue1, DirectExchange directExchange){ |
| return BindingBuilder.bind(directQueue1).to(directExchange).with("red"); |
| } |
| |
| @Bean |
| public Binding directQueue1BindingBlue(Queue directQueue1, DirectExchange directExchange){ |
| return BindingBuilder.bind(directQueue1).to(directExchange).with("blue"); |
| } |
| |
| } |
注解形式
| @RabbitListener(bindings = @QueueBinding( |
| value = @Queue(name = "direct.queue1", durable = "true"), |
| exchange = @Exchange(name = "hmall.direct", type = ExchangeTypes.DIRECT), |
| key = {"blue", "red"} |
| )) |
| public void listenDirectQueue1(String msg){ |
| System.err.println("消费者2 收到了direct.queue1的消息:{" + msg + "}"); |
| } |
| |
| @RabbitListener(bindings = @QueueBinding( |
| value = @Queue(name = "direct.queue2", durable = "true"), |
| exchange = @Exchange(name = "hmall.direct", type = ExchangeTypes.DIRECT), |
| key = {"yellow", "red"} |
| )) |
| public void listenDirectQueue2(String msg){ |
| System.err.println("消费者2 收到了direct.queue2的消息:{" + msg + "}"); |
| } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)