一个小练习

创建一个springboot工程

该练习可以分为一个生产者,两个消费者,一个交换机
可以运用发布订阅模式来实现
创建一个消费者:
package com.wyj;
import com.alibaba.fastjson.JSON;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
/**
* @author 王逸君
* @version 1.0
* @date 2021/4/20 19:01
*/
@RestController
public class Test {
@Autowired
private RabbitTemplate rabbitTemplate;
@GetMapping("/hello")
public String hello(){
System.out.println("下单成功");
HashMap<Object, Object> map = new HashMap<>();
map.put("id",1);
map.put("num",300);
map.put("price",6000);
/**
* String routingKey
* Object message
*/
rabbitTemplate.convertAndSend("qy129_exchange_fanout","",JSON.toJSONString(map));
return "下单成功";
}
}
两个消费者,其中支付系统为:
package com.wyj.pay;
import com.alibaba.fastjson.JSON;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import java.util.Map;
/**
* @author 王逸君
* @version 1.0
* @date 2021/4/20 19:37
*/
@Component
public class Test {
@RabbitListener(queues = {"qy129_exchange01"})
public void pay(String msg){
Map map = JSON.parseObject(msg, Map.class);
System.out.println("应收款为:"+map.get("price"));
System.out.println("支付系统,已支付");
}
}
库存系统为:
package com.wyj.inventory;
import com.alibaba.fastjson.JSON;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import java.util.Map;
/**
* @author 王逸君
* @version 1.0
* @date 2021/4/20 19:06
*/
@Component
public class Test {
@RabbitListener(queues = {"qy129_exchange02"})
public void inventory(String msg){
Map map = JSON.parseObject(msg, Map.class);
System.out.println("商品编号为:"+map.get("id")+",出库数量为:"+map.get("num"));
System.out.println("库存系统,出货成功");
}
}
本文展示了如何使用SpringBoot构建一个基于RabbitMQ的发布订阅模式应用,包括一个生产者、两个消费者(支付系统和库存系统)。当下单成功时,生产者将订单信息发送到交换机,交换机再将消息路由到相应的队列,被消费者监听并处理。支付系统接收到消息后处理支付,库存系统则处理商品出库。
50万+

被折叠的 条评论
为什么被折叠?



