SpringBoot-RabbitMQ直接交换模式

生产者

配置生产者

/**
 * @author BNTang
 */
@Configuration
public class RoutingDirectConfig {

    /**
     * 声明交换机
     *
     * @return 交换机
     */
    @Bean
    public DirectExchange directExchange() {
        return new DirectExchange("directs");
    }

    /**
     * 声明队列1 绑定info 和 warm
     *
     * @return 队列1
     */
    @Bean
    public Queue queue1() {
        return new Queue("queue1");
    }

    /**
     * 声明队列2
     *
     * @return 队列2
     */
    @Bean
    public Queue queue2() {
        return new Queue("queue2");
    }

    /**
     * 把队列1绑定到交换机里面指定info的路由key
     *
     * @return 交换机
     */
    @Bean
    public Binding binding1() {
        return BindingBuilder.bind(queue1()).to(directExchange()).with("info");
    }

    /**
     * 把队列2绑定到交换机里面指定error的路由key
     *
     * @return 交换机
     */
    @Bean
    public Binding binding2() {
        return BindingBuilder.bind(queue2()).to(directExchange()).with("error");
    }
}

发送消息

@Test
public void testRoutingDirect() {
    this.rabbitTemplate.convertAndSend("directs", "info", "info 的日志信息");
    this.rabbitTemplate.convertAndSend("directs", "warm", "warm 的日志信息");
    this.rabbitTemplate.convertAndSend("directs", "debug", "debug 的日志信息");
    this.rabbitTemplate.convertAndSend("directs", "error", "error 的日志信息");
    System.out.println("消息发送成功");
}

消费者

消费消息

/**
 * @author BNTang
 */
@Component
public class RoutingDirectConsumer {

    @RabbitListener(bindings = {
            @QueueBinding(
                    value = @Queue("queue1"),
                    key = {"info", "warm"},
                    exchange = @Exchange(name = "directs", type = ExchangeTypes.DIRECT)
            )
    })
    public void receive1(String message) {
        System.out.println("消费者【1】接收到消息:" + message);
    }

    @RabbitListener(bindings = {
            @QueueBinding(
                    value = @Queue("queue2"),
                    key = {"debug", "error"},
                    exchange = @Exchange(name = "directs", type = ExchangeTypes.DIRECT)
            )
    })
    public void receive2(String message) {
        System.out.println("消费者【2】接收到消息:" + message);
    }
}

测试方式同之前章节的一样。

posted @   BNTang  阅读(117)  评论(0编辑  收藏  举报
编辑推荐:
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· AI 智能体引爆开源社区「GitHub 热点速览」
· 写一个简单的SQL生成工具
点击右上角即可分享
微信分享提示