基于javaweb+mysql的ssm+maven网上图书商城系统(java+ssm+jsp+mysql+redis+easyui)
运行环境
Java≥8、MySQL≥5.7、Tomcat≥8
开发工具
eclipse/idea/myeclipse/sts等均可配置运行
适用
课程设计,大作业,毕业设计,项目练习,学习演示等
功能说明
基于javaweb+mysql的SSM+Maven网上图书商城系统(java+ssm+jsp+mysql+redis+easyui)
这个项目涉及到Shiro整合JWT、秒杀功能所具备的基本要求(限流、乐观锁、接口隐藏、JMeter高并发测试等等)、消息中间件RabbitMQ的异步邮件通知和死信队列、沙箱支付宝模拟支付等等技术亮点。
项目功能:该项目分为买家、卖家、管理员三个角色。买家角色的功能:登录、注册、浏览图书、管理购物车、结算订单、支付订单、查看订单、修改个人信息等等功能。
卖家角色的功能:登录、注册、浏览商品、管理自己发布的图书、管理收到的订单、查看自己的收益详情等等。管理员角色的功能:登录、管理所有用户信息、管理权限信息、管理所有卖家发布的图书、管理所有订单信息、管理所有支付信息、查看总共收益详情等等。
应用技术:SSM + Jsp + MySQL + Redis + JWT + Shiro + EasyUI等
运行环境:Eclipse/IntelliJ IDEA + MySQL5.7 + Maven3.6.3+ JDK1.8 + Redis5.0.5+ Tomcat8.5 +
// + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
// String form = "";
// try {
// form = alipayClient.pageExecute(request).getBody(); // 调用SDK生成表单
// } catch (AlipayApiException e) {
// e.printStackTrace();
// }
// httpResponse.setContentType("text/html;charset=" + CHARSET);
// httpResponse.getWriter().write(form);// 直接将完整的表单html输出到页面
// httpResponse.getWriter().flush();
// httpResponse.getWriter().close();
// }
//
//
//
// /**
// * 回调页面
// * @param request
// * @param response
// * @return
// * @throws IOException
// * @throws AlipayApiException
// */
// @GetMapping(value = "/common/alipay/returnUrl")
// public void returnUrl(HttpServletRequest request, HttpServletResponse response)
// throws IOException, AlipayApiException {
// logger.info("=================================同步回调=====================================");
//
// // 获取支付宝GET过来反馈信息
// Map<String, String> params = new HashMap<String, String>();
// Map<String, String[]> requestParams = request.getParameterMap();
// for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
// String name = (String) iter.next();
// String[] values = (String[]) requestParams.get(name);
// String valueStr = "";
// //把每个key对应的值取出来
// for (int i = 0; i < values.length; i++) {
// valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
// }
// // 乱码解决,这段代码在出现乱码时使用
// valueStr = new String(valueStr.getBytes("utf-8"), "utf-8");
// params.put(name, valueStr);
// }
*/
/**
* 库存Stock控制类
*/
@Controller
public class StockController {
@Autowired
private IStockService stockService;
/**
* 库存列表页面
* @param model
* @return
*/
@GetMapping("/admin/stock/list")
public String list(Model model){
return stockService.toStockList(model);
}
/**
* 获取库存列表信息
* @param page
* @param name
* @return
*/
@PostMapping("/admin/stock/list")
@ResponseBody
public Map<String, Object> list(Page page, String name){
return stockService.getStockList(page, name);
}
/**
* 添加库存信息操作处理
* @param stock
* @return
*/
@PostMapping("/admin/stock/add")
@ResponseBody
public ResponseVo<Boolean> add(Stock stock){
return stockService.addStock(stock);
}
//
// //发送RabbitMQ异步消息 5分钟后检查是否已支付成功,如果没有,则取消订单
try{
//将Java对象匹配JSON结构
//对象转化为字节码 把对象转化为字节码后,把字节码传输过去再转化为对象
byte[] bytes = CommonUtil.getBytesFromObject(selectedPay);
//发送消息
amqpTemplate.convertAndSend("my_normal_exchange", "my_ttl_dlx", bytes);
}catch (Exception e){
//邮件发送失败
e.printStackTrace();
}
//
//
// //商户订单号,商户网站订单系统中唯一订单号,必填
// //生成随机Id
// String out_trade_no = selectedPay.getPayNo();
// //付款金额,必填
// String total_amount = String.valueOf(selectedPay.getTotalAmount());
// //订单名称,必填
// String subject ="网上图书商城订单支付";
// //商品描述,可空
// String body = "尊敬的用户:"+user.getUsername()+",欢迎您在网上图书商城下单!";
// request.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
// + "\"total_amount\":\""+ total_amount +"\","
// + "\"subject\":\""+ subject +"\","
// + "\"body\":\""+ body +"\","
// + "\"timeout_express\":\""+"5m"+"\","
// + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
// String form = "";
// try {
// form = alipayClient.pageExecute(request).getBody(); // 调用SDK生成表单
// } catch (AlipayApiException e) {
// e.printStackTrace();
// }
// httpResponse.setContentType("text/html;charset=" + CHARSET);
// httpResponse.getWriter().write(form);// 直接将完整的表单html输出到页面
// httpResponse.getWriter().flush();
// httpResponse.getWriter().close();
// }
//
//
@PostMapping("/admin/user/delete")
@ResponseBody
public ResponseVo<Boolean> delete(String ids){
return userService.deleteUser(ids);
}
}
/**
*/
/**
* 前台图书Book控制类
*/
@Controller
public class HomeBookController {
@Autowired
private IBookService bookService;
/**
* 前台更多图书展示页面
* @return
*/
@GetMapping("/home/book/more")
public String more(){
return "home/book/more";
}
/**
* 前台图书详情展示页面
* @param model
// @Autowired
// private PayDao payDao;
//
// @Autowired
// private ICartService cartService;
//
// @Autowired
// private OrderDao orderDao;
//
// @Autowired
// private IOrderService orderService;
//
// @Autowired
// private IPayService payService;
//
// @Autowired
// private IPayItemService payItemService;
//
// @Autowired
// private IBookService bookService;
//
@Autowired
private AmqpTemplate amqpTemplate;
//
// /**
// * 支付页面
// * @param req
// * @param httpResponse
// * @throws IOException
// */
// @GetMapping("/common/alipay/pay")
// public void alipay(HttpServletRequest req, HttpServletResponse httpResponse) throws IOException {
// User user = (User) SecurityUtils.getSubject().getPrincipal();
// if(user == null){
// throw new RuntimeException("还未登录或会话失效,请重新登录!");
// }
// String payId = (String) req.getSession().getAttribute(RuntimeConstant.payIdSession);
// if(CommonUtil.isEmpty(payId)){
// throw new RuntimeException("支付会话失效,请重新操作!");
// }
// QueryWrapper<Pay> queryWrapper = new QueryWrapper<>();
// queryWrapper.eq("user_id", user.getId());
// queryWrapper.eq("id", payId);
// Pay selectedPay = payDao.selectOne(queryWrapper);
if(row <= 0){
throw new RuntimeException("创建支付详情数据失败,请联系管理员!");
}
// 8.把支付id存入session中
request.getSession().setAttribute(RuntimeConstant.payIdSession, String.valueOf(payId));
request.getSession().setAttribute(RuntimeConstant.orderIdSession, String.valueOf(order.getId()));
return ResponseVo.successByMsg(true, "成功提交订单!");
}
@Override
public List<Order> updateOrderStateAfterPay(Pay pay) {
Set<Long> orderIdSet = new HashSet<>();
QueryWrapper<PayItem> payItemQueryWrapper = new QueryWrapper<>();
payItemQueryWrapper.eq("pay_id", pay.getId());
List<PayItem> payItemList = payItemDao.selectList(payItemQueryWrapper);
if(payItemList == null || payItemList.size() == 0){
throw new RuntimeException("支付成功,但订单状态异常,下单失败,请及时联系管理员解决!");
}
payItemList.forEach(e->{orderIdSet.add(e.getOrderId());});
List<Order> orderList = orderDao.selectBatchIds(orderIdSet);
if(orderList == null || orderList.size() == 0){
throw new RuntimeException("支付成功,但订单状态异常,下单失败,请及时联系管理员解决!");
}
for(Order order : orderList){
order.setState(OrderStateEnum.PAYED.getCode());
if(orderDao.updateById(order) <= 0){
throw new RuntimeException("支付成功,但订单状态异常,下单失败,请及时联系管理员解决!");
}
}
return orderList;
}
@Override
public ResponseVo<Map<String, Object>> getUserOrderData(Page page) {
Map<String, Object> ret = new HashMap<>();
User user = (User) SecurityUtils.getSubject().getPrincipal();
if(user == null){
return ResponseVo.errorByMsg(CodeMsg.USER_SESSION_EXPIRED);
}
Map<String, Object> queryMap = new HashMap<>();
if(page != null){
page.setRows(1); //每页1条数据
queryMap.put("offset", page.getOffset());
queryMap.put("pageSize", page.getRows());
}
queryMap.put("customerId", user.getId());
queryMap.put("isDeleted", OrderDeleteEnum.NO.getCode());
List<Order> orderList = orderDao.selectAll(queryMap);
ret.put("orderList", orderList);
ret.put("page", page.getPage());
ret.put("totalCount", orderDao.getAllTotal(queryMap));
// private final String RETURN_URL = "http://localhost:8080/OnlineBookShop/common/alipay/returnUrl";
// //==========================这些信息未经作者允许,不允许分享使用!!!=================================
//
// private final Logger logger = LoggerFactory.getLogger(AliPayController_backup.class);
//
// @Autowired
// private PayDao payDao;
//
// @Autowired
// private ICartService cartService;
//
// @Autowired
// private OrderDao orderDao;
//
// @Autowired
// private IOrderService orderService;
//
// @Autowired
// private IPayService payService;
//
// @Autowired
// private IPayItemService payItemService;
//
// @Autowired
// private IBookService bookService;
//
@Autowired
private AmqpTemplate amqpTemplate;
//
// /**
// * 支付页面
// * @param req
// * @param httpResponse
// * @throws IOException
// */
// @GetMapping("/common/alipay/pay")
// public void alipay(HttpServletRequest req, HttpServletResponse httpResponse) throws IOException {
// User user = (User) SecurityUtils.getSubject().getPrincipal();
// if(user == null){
// throw new RuntimeException("还未登录或会话失效,请重新登录!");
// }
// String payId = (String) req.getSession().getAttribute(RuntimeConstant.payIdSession);
// if(CommonUtil.isEmpty(payId)){
// throw new RuntimeException("支付会话失效,请重新操作!");
// }
// QueryWrapper<Pay> queryWrapper = new QueryWrapper<>();
// queryWrapper.eq("user_id", user.getId());
// queryWrapper.eq("id", payId);
// Pay selectedPay = payDao.selectOne(queryWrapper);
}
}
/**
* 返回指定格式的日期
* @param str_date
* @param formatter
* @return
*/
public static Date getFormatterDate(String str_date, String formatter){
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(formatter);
try{
Date date = simpleDateFormat.parse(str_date);
return date;
}catch(Exception e){
e.printStackTrace();
return null;
}
}
/**
* 截取文件路径中的日期部分
* @param filePath
* @return
*/
public static String getFileDate(String filePath){
filePath = filePath.substring(0,filePath.lastIndexOf("/")); //把路径去掉文件名部分
String fileDate = filePath.substring(filePath.lastIndexOf("/") + 1);
return fileDate;
}
/**
* 返回指定格式的日期字符串
* @param date
* @param formatter
* @return
*/
public static String getFormatterDate(Date date, String formatter){
SimpleDateFormat sdf = new SimpleDateFormat(formatter);
return sdf.format(date);
}
/**
return ResponseVo.errorByMsg(CodeMsg.USER_SESSION_EXPIRED);
}else if(e.getMessage().equals("支付会话失效,请重新操作!")){
return ResponseVo.errorByMsg(CodeMsg.PAY_SESSION_EXPIRED);
}else if(e.getMessage().equals("数据非法,支付失败,请重新操作!")){
return ResponseVo.errorByMsg(CodeMsg.PAY_DATA_ERROR);
}else if(e.getMessage().equals("支付成功,但数据异常,下单失败,请及时联系管理员解决!")){
return ResponseVo.errorByMsg(CodeMsg.PAY_SUCCESS_BUT_DATA_ERROR);
}else if(e.getMessage().equals("支付成功,但支付状态异常,下单失败,请及时联系管理员解决!")){
return ResponseVo.errorByMsg(CodeMsg.PAY_SUCCESS_BUT_PAY_STATE_ERROR);
}else if(e.getMessage().equals("支付成功,但订单状态异常,下单失败,请及时联系管理员解决!")){
return ResponseVo.errorByMsg(CodeMsg.PAY_SUCCESS_BUT_ORDER_STATE_ERROR);
}
}
return ResponseVo.errorByMsg(CodeMsg.SYSTEM_ERROR);
}
}
/**
*/
/**
* 后台图书Book控制类
*/
@Controller
public class BookController {
@Autowired
private IBookService bookService;
/**
amqpTemplate.convertAndSend("my_normal_exchange", "my_ttl_dlx", bytes);
}catch (Exception e){
//邮件发送失败
e.printStackTrace();
}
//
//
// //商户订单号,商户网站订单系统中唯一订单号,必填
// //生成随机Id
// String out_trade_no = selectedPay.getPayNo();
// //付款金额,必填
// String total_amount = String.valueOf(selectedPay.getTotalAmount());
// //订单名称,必填
// String subject ="网上图书商城订单支付";
// //商品描述,可空
// String body = "尊敬的用户:"+user.getUsername()+",欢迎您在网上图书商城下单!";
// request.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
// + "\"total_amount\":\""+ total_amount +"\","
// + "\"subject\":\""+ subject +"\","
// + "\"body\":\""+ body +"\","
// + "\"timeout_express\":\""+"5m"+"\","
// + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
// String form = "";
// try {
// form = alipayClient.pageExecute(request).getBody(); // 调用SDK生成表单
// } catch (AlipayApiException e) {
// e.printStackTrace();
// }
// httpResponse.setContentType("text/html;charset=" + CHARSET);
// httpResponse.getWriter().write(form);// 直接将完整的表单html输出到页面
// httpResponse.getWriter().flush();
// httpResponse.getWriter().close();
// }
//
//
// /**
// * 继续支付页面
// * @param orderId
// * @param req
// * @param httpResponse
// * @throws IOException
ret.put("totalCount", orderDao.getAllTotal(queryMap));
page.setTotalCount(orderDao.getAllTotal(queryMap));
ret.put("totalPage", page.getTotalPage());
ret.put("sendTotal", orderDao.getCountByOrderState(user.getId(), OrderStateEnum.SEND.getCode()));
ret.put("signTotal", orderDao.getCountByOrderState(user.getId(), OrderStateEnum.SIGN.getCode()));
return ResponseVo.success(ret);
}
@Override
public ResponseVo<Boolean> delOrderByUser(String orderId) {
User user = (User) SecurityUtils.getSubject().getPrincipal();
if(user == null){
return ResponseVo.errorByMsg(CodeMsg.USER_SESSION_EXPIRED);
}
if(CommonUtil.isEmpty(orderId)){
return ResponseVo.errorByMsg(CodeMsg.DATA_ERROR);
}
Order selectedOrder = orderDao.selectById(orderId);
if(selectedOrder == null){
return ResponseVo.errorByMsg(CodeMsg.ORDER_NOT_EXIST);
}
selectedOrder.setCustomerDelete(OrderDeleteEnum.YES.getCode());
if(orderDao.updateById(selectedOrder) <= 0){
return ResponseVo.errorByMsg(CodeMsg.ORDER_DELETE_ERROR);
}
return ResponseVo.successByMsg(true, "成功删除订单!");
}
@Override
public Map<String, Object> getOrderList(Page page, String customerName, String sellerName, Integer state, String orderNo) {
Map<String, Object> ret = new HashMap<>();
Map<String, Object> queryMap = new HashMap<>();
if(!CommonUtil.isEmpty(customerName)){
queryMap.put("customerName", customerName);
}
if(!CommonUtil.isEmpty(sellerName)){
queryMap.put("sellerName", sellerName);
}
if(!CommonUtil.isEmpty(orderNo)){
queryMap.put("orderNo", orderNo);
}
if(state != null && state.intValue() != -1){
queryMap.put("state", state);
}
queryMap.put("offset", page.getOffset());
queryMap.put("pageSize", page.getRows());
//获取当前登录的用户
User user = (User) SecurityUtils.getSubject().getPrincipal();
if(user == null){
return ret;
}
if(RoleEnum.SELLER.getCode().equals(user.getRoleId())){
//如果是卖家角色,只能查看到自己的订单信息
}
}else if("sub".equals(type)){
//数量-1
if(selectedCart.getQuantity().intValue() == 1){
return ResponseVo.errorByMsg(CodeMsg.BUY_NUM_LT_MIN);
}
selectedCart.setQuantity(selectedCart.getQuantity()-1);
}else{
return ResponseVo.errorByMsg(CodeMsg.DATA_ERROR);
}
//修改数据库中的购物车信息
if(cartDao.updateById(selectedCart) < 0){
return ResponseVo.errorByMsg(CodeMsg.CART_EDIT_ERROR);
}
return ResponseVo.success(true);
}
@Override
public Integer getCartTotal(String userId) {
if(CommonUtil.isEmpty(userId)){
return 0;
}
QueryWrapper<Cart> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("user_id", userId);
List<Cart> cartList = cartDao.selectList(queryWrapper);
return cartList.size();
}
@Override
public void deleteCartAfterPay(List<Order> orderList) {
if(orderList != null && orderList.size() > 0){
Long userId = orderList.get(0).getCustomerId();
//获取本次购买所有的订单详情
List<OrderItem> orderItemList = new ArrayList<>();
for(Order order : orderList){
QueryWrapper<OrderItem> orderItemQueryWrapper = new QueryWrapper<>();
orderItemQueryWrapper.eq("order_id", order.getId());
List<OrderItem> selectedOrderItemList = orderItemDao.selectList(orderItemQueryWrapper);
selectedOrderItemList.forEach(e->{orderItemList.add(e);});
}
Set<Long> bookIdSet = new HashSet<>();
orderItemList.forEach(e->{bookIdSet.add(e.getBookId());});
bookIdSet.forEach(e->{
QueryWrapper<Cart> cartQueryWrapper = new QueryWrapper<>();
cartQueryWrapper.eq("book_id", e);
/**
* 前台用户我的订单页面
* @return
*/
@GetMapping("/home/user/my_order")
public String myOrder(){
return "home/user/order";
}
/**
* 获取用户我的订单的数据
* @param page
* @return
*/
@PostMapping("/home/user/my_order")
@ResponseBody
public ResponseVo<Map<String, Object>> getMyOrderData(@RequestBody Page page){
return orderService.getUserOrderData(page);
}
/**
* 用户删除订单操作处理
* @param orderId
* @return
*/
@PostMapping("/home/user/del_order")
@ResponseBody
public ResponseVo<Boolean> delOrderByUser(String orderId){
return orderService.delOrderByUser(orderId);
}
}
/**
*/
if(cartDao.updateById(selectedCart) < 0){
return ResponseVo.errorByMsg(CodeMsg.CART_EDIT_ERROR);
}
return ResponseVo.success(true);
}
@Override
public Integer getCartTotal(String userId) {
if(CommonUtil.isEmpty(userId)){
return 0;
}
QueryWrapper<Cart> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("user_id", userId);
List<Cart> cartList = cartDao.selectList(queryWrapper);
return cartList.size();
}
@Override
public void deleteCartAfterPay(List<Order> orderList) {
if(orderList != null && orderList.size() > 0){
Long userId = orderList.get(0).getCustomerId();
//获取本次购买所有的订单详情
List<OrderItem> orderItemList = new ArrayList<>();
for(Order order : orderList){
QueryWrapper<OrderItem> orderItemQueryWrapper = new QueryWrapper<>();
orderItemQueryWrapper.eq("order_id", order.getId());
List<OrderItem> selectedOrderItemList = orderItemDao.selectList(orderItemQueryWrapper);
selectedOrderItemList.forEach(e->{orderItemList.add(e);});
}
Set<Long> bookIdSet = new HashSet<>();
orderItemList.forEach(e->{bookIdSet.add(e.getBookId());});
bookIdSet.forEach(e->{
QueryWrapper<Cart> cartQueryWrapper = new QueryWrapper<>();
cartQueryWrapper.eq("book_id", e);
cartQueryWrapper.eq("user_id", userId);
cartDao.delete(cartQueryWrapper);
});
}
}
}
// @Autowired
// private IPayItemService payItemService;
//
// @Autowired
// private IBookService bookService;
//
@Autowired
private AmqpTemplate amqpTemplate;
//
// /**
// * 支付页面
// * @param req
// * @param httpResponse
// * @throws IOException
// */
// @GetMapping("/common/alipay/pay")
// public void alipay(HttpServletRequest req, HttpServletResponse httpResponse) throws IOException {
// User user = (User) SecurityUtils.getSubject().getPrincipal();
// if(user == null){
// throw new RuntimeException("还未登录或会话失效,请重新登录!");
// }
// String payId = (String) req.getSession().getAttribute(RuntimeConstant.payIdSession);
// if(CommonUtil.isEmpty(payId)){
// throw new RuntimeException("支付会话失效,请重新操作!");
// }
// QueryWrapper<Pay> queryWrapper = new QueryWrapper<>();
// queryWrapper.eq("user_id", user.getId());
// queryWrapper.eq("id", payId);
// Pay selectedPay = payDao.selectOne(queryWrapper);
// if(selectedPay == null){
// throw new RuntimeException("数据非法,支付失败,请重新操作!");
// }
// Random r = new Random();
// //实例化客户端,填入所需参数
// AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL, APP_ID, APP_PRIVATE_KEY, FORMAT, CHARSET, ALIPAY_PUBLIC_KEY, SIGN_TYPE);
// AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
// //在公共参数中设置回跳和通知地址
// request.setReturnUrl(RETURN_URL);
// //request.setNotifyUrl(NOTIFY_URL);
//
// //发送RabbitMQ异步消息 5分钟后检查是否已支付成功,如果没有,则取消订单
try{
//将Java对象匹配JSON结构
//对象转化为字节码 把对象转化为字节码后,把字节码传输过去再转化为对象
byte[] bytes = CommonUtil.getBytesFromObject(selectedPay);
//发送消息
amqpTemplate.convertAndSend("my_normal_exchange", "my_ttl_dlx", bytes);
}catch (Exception e){
//邮件发送失败
e.printStackTrace();
// @Autowired
// private IBookService bookService;
//
@Autowired
private AmqpTemplate amqpTemplate;
//
// /**
// * 支付页面
// * @param req
// * @param httpResponse
// * @throws IOException
// */
// @GetMapping("/common/alipay/pay")
// public void alipay(HttpServletRequest req, HttpServletResponse httpResponse) throws IOException {
// User user = (User) SecurityUtils.getSubject().getPrincipal();
// if(user == null){
// throw new RuntimeException("还未登录或会话失效,请重新登录!");
// }
// String payId = (String) req.getSession().getAttribute(RuntimeConstant.payIdSession);
// if(CommonUtil.isEmpty(payId)){
// throw new RuntimeException("支付会话失效,请重新操作!");
// }
// QueryWrapper<Pay> queryWrapper = new QueryWrapper<>();
// queryWrapper.eq("user_id", user.getId());
// queryWrapper.eq("id", payId);
// Pay selectedPay = payDao.selectOne(queryWrapper);
// if(selectedPay == null){
// throw new RuntimeException("数据非法,支付失败,请重新操作!");
// }
// Random r = new Random();
// //实例化客户端,填入所需参数
// AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL, APP_ID, APP_PRIVATE_KEY, FORMAT, CHARSET, ALIPAY_PUBLIC_KEY, SIGN_TYPE);
// AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
// //在公共参数中设置回跳和通知地址
// request.setReturnUrl(RETURN_URL);
// //request.setNotifyUrl(NOTIFY_URL);
//
// //发送RabbitMQ异步消息 5分钟后检查是否已支付成功,如果没有,则取消订单
try{
//将Java对象匹配JSON结构
//对象转化为字节码 把对象转化为字节码后,把字节码传输过去再转化为对象
byte[] bytes = CommonUtil.getBytesFromObject(selectedPay);
//发送消息
amqpTemplate.convertAndSend("my_normal_exchange", "my_ttl_dlx", bytes);
}catch (Exception e){
//邮件发送失败
e.printStackTrace();
@Autowired
private OrderItemDao orderItemDao;
@Autowired
private IUserService userService;
//用户和图书MD5加密的redis键名模板
private static final String USER_BOOK_KEY_TEMPLATE = "user_%d_book_%d";
//盐
private static final String salt = "yang yang ya";
//创建令牌桶实例
private RateLimiter rateLimiter = RateLimiter.create(10); //1s向令牌桶中放置10个令牌
private final Logger logger = LoggerFactory.getLogger(CartServiceImpl.class);
@Override
public ResponseVo<Boolean> addCart(Cart cart, HttpServletRequest request) {
//限流处理 设置一个等待时间,如果在等待的时间内获取到了token 令牌,则处理业务,如果在等待时间内没有获取到响应token则抛弃
if(!rateLimiter.tryAcquire(2, TimeUnit.SECONDS)){
//2s内没获取到令牌桶中的令牌,选择抛弃
logger.info("请求被限流,直接抛弃......");
return ResponseVo.errorByMsg(CodeMsg.REQUEST_LIMIT);
}
logger.info("接收请求,执行后续业务......");
User user = (User) SecurityUtils.getSubject().getPrincipal();
if(user == null){
return ResponseVo.errorByMsg(CodeMsg.USER_SESSION_EXPIRED);
}
//判断当前用户在一定时间内的访问次数,为0次则用户数据异常
int count = userService.saveUserCount(user.getId());
if(count == 0){
return ResponseVo.errorByMsg(CodeMsg.USER_SESSION_EXPIRED);
}
//大于10次则拒绝访问
if(count > 10){
return ResponseVo.errorByMsg(CodeMsg.REQUEST_COUNT_MANY);
}
logger.info("请求被限流,直接抛弃......");
return ResponseVo.errorByMsg(CodeMsg.REQUEST_LIMIT);
}
logger.info("接收请求,执行后续业务......");
User user = (User) SecurityUtils.getSubject().getPrincipal();
if(user == null){
return ResponseVo.errorByMsg(CodeMsg.USER_SESSION_EXPIRED);
}
//判断当前用户在一定时间内的访问次数,为0次则用户数据异常
int count = userService.saveUserCount(user.getId());
if(count == 0){
return ResponseVo.errorByMsg(CodeMsg.USER_SESSION_EXPIRED);
}
//大于10次则拒绝访问
if(count > 10){
return ResponseVo.errorByMsg(CodeMsg.REQUEST_COUNT_MANY);
}
cart.setUserId(user.getId());
//进行统一表单验证
CodeMsg validate = ValidateEntityUtil.validate(cart);
if(!validate.getCode().equals(CodeMsg.SUCCESS.getCode())){
return ResponseVo.errorByMsg(validate);
}
//判断MD5加密信息是否合法,不合法,则是用脚本访问接口,直接拒绝
String redisKey = String.format(USER_BOOK_KEY_TEMPLATE, user.getId(), cart.getBookId().longValue());
String md5 = stringRedisTemplate.opsForValue().get(redisKey);
//判断MD5加密信息是否为空
if(CommonUtil.isEmpty(md5)){
return ResponseVo.errorByMsg(CodeMsg.ADD_CART_BUST);
}
String md5Token = "";
Cookie[] cookies = request.getCookies();
if(cookies != null && cookies.length > 0){
for (Cookie cookie : cookies) {
if ("md5_token".equals(cookie.getName())) {
md5Token = cookie.getValue();
}
}
}
//判断MD5加密信息是否合法
if(!md5.equals(md5Token)){
return ResponseVo.errorByMsg(CodeMsg.ADD_CART_ILLEGAL);
}
//根据id获取图书信息
Map<String, Object> queryMap = new HashMap<>();
queryMap.put("id", cart.getBookId());
List<Book> selectedBook = bookDao.getBookList(queryMap);
if(selectedBook == null || selectedBook.size() != 1){
return ResponseVo.errorByMsg(CodeMsg.BOOK_NOT_EXIST);
}