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

}

最后运行 成功接收到消息

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

相关推荐
高兴达38 分钟前
RPC--Netty客户端实现
java·spring·rpc
重庆小透明1 小时前
力扣刷题记录【1】146.LRU缓存
java·后端·学习·算法·leetcode·缓存
lang201509281 小时前
Reactor操作符的共享与复用
java
TTc_1 小时前
@Transactional事务注解的批量回滚机制
java·事务
wei_shuo2 小时前
飞算 JavaAI 开发助手:深度学习驱动下的 Java 全链路智能开发新范式
java·开发语言·飞算javaai
欧阳秦穆3 小时前
apoc-5.24.0-extended.jar 和 apoc-4.4.0.36-all.jar 啥区别
java·jar
岁忧3 小时前
(LeetCode 面试经典 150 题 ) 58. 最后一个单词的长度 (字符串)
java·c++·算法·leetcode·面试·go
Java初学者小白3 小时前
秋招Day14 - Redis - 应用
java·数据库·redis·缓存
代码老y3 小时前
Spring Boot + 本地部署大模型实现:优化与性能提升
java·spring boot·后端
GodKeyNet3 小时前
设计模式-桥接模式
java·设计模式·桥接模式