电商项目mall学习(7)Springboot+RabbitMQ
2020-06-26 本文已影响0人
xywh
参考链接
http://www.macrozheng.com/#/architect/mall_arch_09
使用框架
1.RabbitMQ
RabbitMQ是一个被广泛使用的开源消息队列。它是轻量级且易于部署的,它能支持多种消息协议。RabbitMQ可以部署在分布式和联合配置中,以满足高规模、高可用性的需求。
使用docker安装RabbitMQ
https://www.jianshu.com/p/7b39d33e674c
业务场景
用于解决用户下单以后,订单超时如何取消订单的问题
- 用户进行下单操作(会有锁定商品库存、使用优惠券、积分一系列的操作);
- 生成订单,获取订单的id;
- 获取到设置的订单超时时间(假设设置的为60分钟不支付取消订单);
- 按订单超时时间发送一个延迟消息给RabbitMQ,让它在订单超时后触发取消订单的操作;
- 如果用户没有支付,进行取消订单操作(释放锁定商品库存、返还优惠券、返回积分一系列操作)。
Springboot中引入Rabbitmq实现延迟消息
1.项目中引入rabbitmq依赖,修改pom.xml
<!--消息队列相关依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
2.修改springboot配置,application.yml增加rabbitmq相关配置,添加在spring节点下
rabbitmq:
host: 192.168.1.150# rabbitmq的连接地址
port: 5672 # rabbitmq的连接端口号
virtual-host: /mall # rabbitmq的虚拟host
username: mall # rabbitmq的用户名
password: mall # rabbitmq的密码
publisher-confirms: true #如果对异步消息需要回调必须设置为true
3.添加消息队列的配置类,定义为枚举类型QueueEnum
用于延迟消息队列及处理取消订单消息队列的常量定义,包括交换机名称、队列名称、路由键名称。
package com.mall.mallmybatis.dto;
/**
* 消息队列枚举配置
* @author wangxing
* @version 2020/6/25 13:17 Administrator
*/
public enum QueueEnum {
/**
* 消息通知队列
* mall.order.direct(取消订单消息队列所绑定的交换机):
* 绑定的队列为mall.order.cancel,一旦有消息以mall.order.cancel为路由键发过来,会发送到此队列。
*/
QUEUE_ORDER_CANCEL("mall.order.direct", "mall.order.cancel", "mall.order.cancel"),
/**
* 消息通知ttl队列
* mall.order.direct.ttl(订单延迟消息队列所绑定的交换机):
* 绑定的队列为mall.order.cancel.ttl,一旦有消息以mall.order.cancel.ttl为路由键发送过来,会转发到此队列,
* 并在此队列保存一定时间,等到超时后会自动将消息发送到mall.order.cancel(取消订单消息消费队列)。
*/
QUEUE_TTL_ORDER_CANCEL("mall.order.direct.ttl", "mall.order.cancel.ttl", "mall.order.cancel.ttl");
/**
* 交换名称
*/
private String exchange;
/**
* 队列名称
*/
private String name;
/**
* 路由键
*/
private String routeKey;
QueueEnum(String exchange, String name, String routeKey) {
this.exchange = exchange;
this.name = name;
this.routeKey = routeKey;
}
public String getExchange() {
return exchange;
}
public String getName() {
return name;
}
public String getRouteKey() {
return routeKey;
}
}
4.添加Rabbitmq配置类RabbitMqConfig
package com.mall.mallmybatis.config;
import com.mall.mallmybatis.dto.QueueEnum;
import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @author wangxing
* @version 2020/6/25 13:19 Administrator
*/
@Configuration
public class RabbitMqConfig {
/**
* 订单消息实际消费队列所绑定的交换机
*/
@Bean
DirectExchange orderDirect() {
return (DirectExchange) ExchangeBuilder
//设立直接交换机名称
.directExchange(QueueEnum.QUEUE_ORDER_CANCEL.getExchange())
//设立持久标记
.durable(true)
.build();
}
/**
* 订单延迟队列队列所绑定的交换机
*/
@Bean
DirectExchange orderTtlDirect() {
return (DirectExchange) ExchangeBuilder
//设立直接交换机名称
.directExchange(QueueEnum.QUEUE_TTL_ORDER_CANCEL.getExchange())
//设立持久标记
.durable(true)
.build();
}
/**
* 订单实际消费队列
*/
@Bean
public Queue orderQueue() {
return new Queue(QueueEnum.QUEUE_ORDER_CANCEL.getName());
}
/**
* 订单延迟队列(死信队列)
*/
@Bean
public Queue orderTtlQueue() {
return QueueBuilder
//创建持久队列构造器
.durable(QueueEnum.QUEUE_TTL_ORDER_CANCEL.getName())
//设置持久队列参数,设置死信交换机
/*
在队列上指定一个Exchange,则在该队列上发生如下情况,
1.消息被拒绝(basic.reject or basic.nack),且requeue=false
2.消息过期而被删除(TTL)
3.消息数量超过队列最大限制而被删除
4.消息总大小超过队列最大限制而被删除
就会把该消息转发到指定的这个exchange;
同时也可以指定一个可选的x-dead-letter-routing-key,表示默认的routing-key,如果没有指定,
则使用消息的routeing-key(也跟指定的exchange有关,如果是Fanout类型的exchange,则会转发到所有绑定到该exchange的所有队列
*/
.withArgument("x-dead-letter-exchange", QueueEnum.QUEUE_ORDER_CANCEL.getExchange())//到期后转发的交换机
.withArgument("x-dead-letter-routing-key", QueueEnum.QUEUE_ORDER_CANCEL.getRouteKey())//到期后转发的路由键
.build();
}
/**
* 将订单队列绑定到交换机
*/
@Bean
Binding orderBinding(DirectExchange orderDirect,Queue orderQueue){
return BindingBuilder
.bind(orderQueue)
.to(orderDirect)
.with(QueueEnum.QUEUE_ORDER_CANCEL.getRouteKey());
}
/**
* 将订单延迟队列绑定到交换机
*/
@Bean
Binding orderTtlBinding(DirectExchange orderTtlDirect,Queue orderTtlQueue){
return BindingBuilder
.bind(orderTtlQueue)
.to(orderTtlDirect)
.with(QueueEnum.QUEUE_TTL_ORDER_CANCEL.getRouteKey());
}
}
5.添加延迟消息发送者CancelOrderSender
用于向订单延迟消息队列(mall.order.cancel.ttl)里发送消息。
package com.mall.mallmybatis.componet;
import com.mall.mallmybatis.dto.QueueEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
* 取消订单消息的发出者
* @author wangxing
* @version 2020/6/25 14:59 Administrator
*/
@Component
public class CancelOrderSender {
private static Logger LOGGER = LoggerFactory.getLogger(CancelOrderSender.class);
@Autowired
private AmqpTemplate amqpTemplate;
public void sendMessage(Long orderId,final long delayTimes){
//给延迟队列发送消息
amqpTemplate.convertAndSend(QueueEnum.QUEUE_TTL_ORDER_CANCEL.getExchange(),
QueueEnum.QUEUE_TTL_ORDER_CANCEL.getRouteKey(), orderId, new MessagePostProcessor() {
@Override
public Message postProcessMessage(Message message) throws AmqpException {
//给消息设置延迟毫秒值
message.getMessageProperties().setExpiration(String.valueOf(delayTimes));
return message;
}
});
LOGGER.info("send delay message orderId:{}",orderId);
}
}
6.添加OmsPortalOrderService接口定义订单部分方法[提交订单/取消订单]
package com.mall.mallmybatis.service;
import com.mall.mallmybatis.common.api.CommonResult;
import com.mall.mallmybatis.dto.OrderParam;
import org.springframework.transaction.annotation.Transactional;
/**
* @author wangxing
* @version 2020/6/25 18:19 Administrator
*/
public interface OmsPortalOrderService {
/**
* 根据提交信息生成订单
*/
@Transactional
CommonResult generateOrder(OrderParam orderParam);
/**
* 取消单个超时订单
*/
@Transactional
void cancelOrder(Long orderId);
}
7.添加取消订单消息的接收者CancelOrderReceiver
用于从取消订单的消息队列(mall.order.cancel)里接收消息。
package com.mall.mallmybatis.componet;
import com.mall.mallmybatis.service.OmsPortalOrderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
* 取消订单消息的处理者
* @author wangxing
* @version 2020/6/25 18:18 Administrator
*/
@Component
@RabbitListener(queues = "mall.order.cancel")//监听消息队列mall.order.cancel获取对应消息
public class CancelOrderReceiver {
private static Logger LOGGER = LoggerFactory.getLogger(CancelOrderReceiver.class);
@Autowired
private OmsPortalOrderService portalOrderService;
@RabbitHandler
public void handle(Long orderId){
LOGGER.info("receive delay message orderId:{}",orderId);
portalOrderService.cancelOrder(orderId);
}
}
8.添加OmsPortalOrderServiceImpl类,实现OmsPortalOrderService接口
package com.mall.mallmybatis.service.impl;
import com.mall.mallmybatis.common.api.CommonResult;
import com.mall.mallmybatis.componet.CancelOrderSender;
import com.mall.mallmybatis.dto.OrderParam;
import com.mall.mallmybatis.service.OmsPortalOrderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* @author wangxing
* @version 2020/6/25 18:25 Administrator
*/
@Service
public class OmsPortalOrderServiceImpl implements OmsPortalOrderService {
private static Logger LOGGER = LoggerFactory.getLogger(OmsPortalOrderServiceImpl.class);
@Autowired
private CancelOrderSender cancelOrderSender;
/**
* 根据提交信息生成订单
*
* @param orderParam
*/
@Override
public CommonResult generateOrder(OrderParam orderParam) {
//todo 执行一系类下单操作,具体参考mall项目
LOGGER.info("process generateOrder");
//下单完成后开启一个延迟消息,用于当用户没有付款时取消订单(orderId应该在下单后生成)
sendDelayMessageCancelOrder(11L);
return CommonResult.success(null, "下单成功");
}
/**
* 取消单个超时订单
*
* @param orderId
*/
@Override
public void cancelOrder(Long orderId) {
//todo 执行一系类取消订单操作,具体参考mall项目
LOGGER.info("process cancelOrder orderId:{}",orderId);
}
/**
* 订单超时时间,假设为10分钟
* 10 * 60 * 1000
*/
private Long DELAY_TIME = 600000L;
private void sendDelayMessageCancelOrder(Long orderId) {
//发送延迟消息
cancelOrderSender.sendMessage(orderId, DELAY_TIME);
}
}
9.添加OmsPortalOrderController定义外界访问接口
package com.mall.mallmybatis.controller;
import com.mall.mallmybatis.dto.OrderParam;
import com.mall.mallmybatis.service.OmsPortalOrderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* @author wangxing
* @version 2020/6/25 18:26 Administrator
*/
@Controller
@Api(tags = "OmsPortalOrderController", description = "订单管理")
@RequestMapping("/order")
public class OmsPortalOrderController {
@Autowired
private OmsPortalOrderService portalOrderService;
@ApiOperation("根据购物车信息生成订单")
@RequestMapping(value = "/generateOrder", method = RequestMethod.POST)
@ResponseBody
public Object generateOrder(@RequestBody OrderParam orderParam) {
return portalOrderService.generateOrder(orderParam);
}
}