RabbitMQ5. 主题模式(Topic)实现和原理步骤讲解,方式5

简单工作队类的实现配置步骤(5步)

  1. 引入AMQP的依赖
  2. 创建配置文件,链接消息队列(port name MQ账号密码
  3. 创建配置类,声明队列
  4. 使用消息生产者发送消息
  5. 使用消息消费者接受消息

1 . 引入AMQP的依赖

	   <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-amqp</artifactId>
        </dependency>
  1. 创建配置文件,链接消息队列(port name MQ账号密码
server:
  port: 9005
spring:
  application:
    name: demo04
  rabbitmq:
    host: 120.55.58.250
    port: 5672
    password: guest
    username: guest

  1. 创建配置类,声明队列
@Configuration
public class TopicQueueConfig {
    public static String queueName01="topic.queue01";
    public static String queueName02="topic.queue02";
    public static String exchangeName="topic.exchange";
    @Bean
    public Queue topicQueue01(){
        return new Queue(queueName01);
    }
    @Bean
    public Queue topicQueue02(){
        return new Queue(queueName02);
    }


    @Bean
    public TopicExchange topicExchange(){
        return new TopicExchange(exchangeName);
    }
    @Bean
    //绑定交换机和队列
    public Binding bindingQueue01(Queue topicQueue01, TopicExchange topicExchange){
        return BindingBuilder.bind(topicQueue01).to(topicExchange).with("topic.A");
    }

    @Bean
    //绑定交换机和队列
    public Binding bindingQueue02(Queue topicQueue02,TopicExchange topicExchange){
        return BindingBuilder.bind(topicQueue02).to(topicExchange).with("topic.#");
    }
}

  1. 使用消息生产者发送消息
@RestController
public class TestController {
    @Autowired
    private RabbitTemplate rabbitTemplate;


    @RequestMapping("/sendMessage01")
    public void sendMessage01(){
        for (int i=1;i<=5;i++){
            rabbitTemplate.convertAndSend("direct.exchange","routingkey.A","路由模式routingA"+i);
        }
    }

    @RequestMapping("/sendMessage02")
    public void sendMessage02(){
        for (int i=1;i<=5;i++){
            rabbitTemplate.convertAndSend("direct.exchange","routingkey.B","路由模式routingB"+i);
        }
    }
}
  1. 使用消息消费者接受消息
@Component
public class ReceiveListener {
    @RabbitListener(queues="direct.queue01")
    public void ReceiveMessage01(String message){
        System.out.println("ReceiveMessage01"+message);
    }

    @RabbitListener(queues="direct.queue02")
    public void ReceiveMessage02(String message){
        System.out.println("ReceiveMessage02"+message);
    }
}

路径

	http://localhost:9005/sendMessage02
    http://localhost:9005/sendMessage01

结果展示

http://localhost:9005/sendMessage01
在这里插入图片描述

http://localhost:9005/sendMessage02
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值