1.环境搭建 (1).安装rabbitmq(适用于centos,windows版本自行百度)源代码:点我0积分下载
docker pull rabbitmq:management
启动
docker run -d --name rabbitmq --publish 5671:5671 --publish 5672:5672 --publish 4369:4369 --publish 25672:25672 --publish 15671:15671 --publish 15672:15672 rabbitmq:management
docker update rabbitmq --restart=always
注:
4369 – erlang发现口
5672 --client端通信口
15672 – 管理界面ui端口
25672 – server间内部通信口
添加rabbitmq的maven依赖
@Configurationpublic class MyMqConfig { @Bean public Queue orderDelayQueue() { //String name, boolean durable, boolean exclusive, boolean autoDelete, @Nullable Map
@Data@AllArgsConstructor@NoArgsConstructorpublic class Order implements Serializable { private String id;//订单编号 private String content;//订单内容 private String state;//订单状态 private String createTime;//创建时间 private String cancelTime;//取消时间}
(3).创建监听队列@Componentpublic class MqListener { @RabbitListener(queues = "order-release-queue") public void listener(Order order, Message message,Channel channel) throws IOException { System.out.println("接收到过期未支付的订单信息"+order); System.out.println("处理过期订单...."); try{ //TODO 判断订单是否已经支付成功,如果支付成功,无需再取消订单 order.setCancelTime(new Date().toString()); order.setState("已过期"); channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);//是否批量签收 }catch (Exception e) { channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);//是否重新入队 } System.out.println("处理后的订单:"+order); }}
(4).创建订单控制器的实现(模拟创建订单)@RestControllerpublic class MqController { @Autowired private RabbitTemplate rabbitTemplate; @GetMapping("/createOrder") public String createOrder(){ //订单下单成功 Order order = new Order(UUID.randomUUID().toString(), "订单商品信息", "未支付",new Date().toString(),null); //给mq发送消息 rabbitTemplate.convertAndSend("order-exchange","order-create",order); return "下单成功"+order; } @GetMapping("/pay/{id}") public String pay(@PathVariable("id") String id){//TODO 修改订单状态为支付成功 return id+"支付成功"; }}