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

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

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

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

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

先编写消费者代码

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

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 规则也要保证相符

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

}

最后运行  成功接收到消息

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

相关推荐

  1. springboot声明(创建RabbitMQ交换机队列

    2024-03-11 11:56:05       26 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-03-11 11:56:05       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-03-11 11:56:05       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-03-11 11:56:05       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-03-11 11:56:05       18 阅读

热门阅读

  1. Hive函数

    2024-03-11 11:56:05       21 阅读
  2. Rust 生命周期符号使用的方法和规律

    2024-03-11 11:56:05       21 阅读
  3. WPF中的DataContext

    2024-03-11 11:56:05       21 阅读
  4. FFmepg--内存IO模式

    2024-03-11 11:56:05       21 阅读
  5. c语言大小字母转换程序

    2024-03-11 11:56:05       23 阅读
  6. Redis Info - CPU

    2024-03-11 11:56:05       21 阅读
  7. Git 开源的版本控制系统-02-base usage 基本用法

    2024-03-11 11:56:05       24 阅读
  8. sass 重写elementui样式

    2024-03-11 11:56:05       22 阅读
  9. PyTorch会在每次.backward()调用时会累积梯度的问题

    2024-03-11 11:56:05       21 阅读