Spring boot简单集成Rabbit MQ

本文介绍了如何在Springboot项目中集成RabbitMQ,包括Windows下的安装步骤,配置文件管理,创建生产者发送消息到queue1队列,以及消费者接收并处理消息。还展示了如何通过API测试源码中的生产者和消费者功能。
摘要由CSDN通过智能技术生成

安装Rabbit MQ

windows下安装Rabbit MQ

Springboot集成Rabbit MQ

  1. 引入依赖

    <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-amqp</artifactId>
            </dependency>
    
  2. 配置文件

    #数据源配置
    spring:
      rabbitmq:
        host: localhost
        port: 5672
        username: admin
        password: admin
    
  3. 创建生产者
    创建队列

    /**
         * 消息队列1
         * @return
         */
        @Bean
        public Queue queue1(){
            return new Queue("queue1",true,false,true);
        }
    

    往队列发消息

    /**
         * 测试取消订单,发送消息
         */
        @GetMapping("/cancel")
        public void cancel(){
    
            //取消订单逻辑省略
    
            //取消订单,发送消息
            Map<String, Object> map = new HashMap<>();
            map.put("order_number","4364756867986666");
            map.put("product_id","2");
            rabbitTemplate.convertAndSend("queue1", map);
        }
    
  4. 创建消费者
    接收消息

    /**
         * 接受消息
         * @throws Exception
         */
        @RabbitHandler
        @RabbitListener(queues = "queue1")
        public void receiverMsg1(HashMap<String, String> msg) throws Exception {
            String order_number = msg.get("order_number");
            String product_id = msg.get("product_id");
            log.info("【消费者】 order_number:【{}】。product_id 【{}】", order_number, product_id);
        }
    
  5. 使用API POST测试

    测试结果

源码

生产者
消费者

  • 7
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值