安装Rabbit MQ
Springboot集成Rabbit MQ
-
引入依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-amqp</artifactId> </dependency>
-
配置文件
#数据源配置 spring: rabbitmq: host: localhost port: 5672 username: admin password: admin
-
创建生产者
创建队列/** * 消息队列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); }
-
创建消费者
接收消息/** * 接受消息 * @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); }
-
使用API POST测试