RabbitMQ - 07 - 通过注解创建队列和交换机

之前消息模型的实现,都是通过rabbitMQ Management 控制台来手动创建 queue 和 exchange 的

在项目开发中有两种方式通过代码声明 创建

一种是通过 Bean 方式,这种代码量较大 稍繁琐

一种是通过注解的方式声明

先编写消费者代码

通过注解绑定了 消息队列,交换机,还有 routing key, 注解会在启动时根据这些名字自动进行创建

java 复制代码
package cn.itcast.mq.lintener;


import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class MQListener {

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "cyh.queue"),
            exchange = @Exchange(name = "cyh.topic",type = ExchangeTypes.TOPIC),
            key = {"#.com"}
    ))
    public void listenTopicQueue3(String message){
        log.info("消费者cyh收到了 : " + message);
    }

}

编写生产者代码

交换机名要跟 消费者绑定的对应

还有 routing key 规则也要保证相符

java 复制代码
package cn.itcast.mq.helloworld;

import org.apache.logging.log4j.message.Message;
import org.junit.jupiter.api.Test;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.messaging.converter.StringMessageConverter;

@SpringBootTest
public class SpringAMQPTest {

    @Autowired
    private RabbitTemplate rabbitTemplate;


    //  topic交换机
    @Test
    void testTopicExchange(){
        String exchangeName = "cyh.topic";
        String message = "hello, topic";
        rabbitTemplate.convertAndSend(exchangeName,"china.com",message);
    }

}

最后运行 成功接收到消息

队列 交换机 也自动创建好了

相关推荐
SeaDhdhdhdhdh6 小时前
MCP Server 搭建与使用指南
java·ai·agent·mcp
YH55269846 小时前
GPT‑5.6 Sol 原本支持 1M 上下文,Codex 现已放开此前限制,如何看待这次调整?
java·jvm·人工智能·gpt·算法·chatgpt
AI_小站7 小时前
刚面完百度的 Agent 开发岗,我才发现:世界就是个巨大的草台班子
java·开发语言·人工智能·spring·百度·langchain
许彰午8 小时前
03-三种开发模式
java·架构
涟漪海洋8 小时前
创建最新的JDK25镜像,非root环境启动
java
Rain的Java大神之路8 小时前
短信接口被狂刷怎么处理
java·运维·后端·web安全·面试·架构·xss
2602_959960929 小时前
谢飞机面试大厂:Spring Boot、JVM、Redis、Kafka、微服务与音视频搜索场景求生实录
java·jvm·spring boot·redis·面试题
Zane1994129 小时前
CAS 与原子类:Java 如何实现无锁编程
java·开发语言
略略略咯咯9 小时前
AI玩具-study
java
xier_ran10 小时前
【infra之路】GPU 存储层次总结:L1 / L2 / HBM
java·网络·数据库