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);
    }

}

最后运行 成功接收到消息

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

相关推荐
用户3126874877206 分钟前
Java 对象内存布局:压缩指针、对齐填充与 JOL 实测
java
东华果汁哥22 分钟前
【Spring AI 实战】从零开始调用大模型接口,构建 Java AI 应用
java·人工智能·spring
Song_RsHt1 小时前
Redis 与微服务,什么场景下无可替代
java·redis·后端·学习·微服务
学长毕设1 小时前
基于SpringBoot的建筑材料管理系统-附源码
java·spring boot·后端
摸爬滚打的小李2 小时前
关于 Arthas
java·后端
砚底藏山河2 小时前
python量化实操:冷热分层存储
java·开发语言·python·金融
yuniko-n2 小时前
【JUC】原子类
java
惊讶的猫2 小时前
Query 改写
java·rag
信誓旦旦的程序猿2 小时前
【Python量化实战宝典 #18】MACD 金叉死叉手册:DIF、DEA、柱体全拆解(Python 可跑)
java·python·股票数据api·股票数据api接口·股票api数据接口·股票量化数据api·股票量化数据接口
Misnearch3 小时前
第7章 面向对象技术
java·开发语言·软考