-
涉及到支付的系统中,必不可少的就是订单,在实际的环境中可能会出现因为网络环境原因或者是操作失误导致重复的请求,下面是一个基于redis的一个控制,有需要的可以作为参考
-
订单分为订单的创建和订单的支付
package com.sunyw.xyz.controller;
import com.alibaba.fastjson.JSON;
import com.sunyw.xyz.bean.OrderReq;
import com.sunyw.xyz.utils.RedisId;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
/**
* @description:订单下单demo 先发下单,根据用户编号跟订单编号做绑定,查询有未支付的不允许再次下单,接口去重
* @author: sunyw
* @version:1.0.0
* @time: 2020-12-11 11:59
*/
@RestController
@Slf4j
public class OrderCreateController {
@Autowired
private RedisTemplate redisTemplate;
@GetMapping("/order/{userId}")
public String orderCreate(@PathVariable String userId) {
Object o = redisTemplate.opsForValue ().get (userId);
if (!ObjectUtils.isEmpty (o)) {
return "订单存在未支付,请勿重复下单";
}
log.info ("--------------------------[{}]开始进行订单创建", userId);
String id = UUID.randomUUID ().toString ();
log.info ("--------------------------[{}]id编号", id);
redisTemplate.opsForValue ().set (userId, id, 1, TimeUnit.MINUTES);
return id;
}
@PostMapping("/pay")
public String pay(@RequestBody OrderReq orderReq) {
log.info ("--------------------------[{}]请求支付信息", JSON.toJSON (orderReq));
if (orderReq != null) {
String userId = orderReq.getUserId ();
log.info ("--------------------------[{}]获取用户号订单,订单编号[{}]", userId, orderReq.getOrderId ());
Object orderId = redisTemplate.opsForValue ().get (userId);
if (ObjectUtils.isEmpty (orderId)) {
return "订单信息为空!";
}
if (!orderId.equals (orderReq.getOrderId ())){
return "订单信息不存在!";
}
log.info ("--------------------------[{}]号订单支付完成,删除订单信息", orderReq.getOrderId ());
redisTemplate.delete (userId);
return "SUCCESS";
}
return "订单信息为空!";
}
}
- 订单实体
package com.sunyw.xyz.bean;
import lombok.Data;
/**
* @description:
* @author:
* @version:1.0.0
* @time: 2020-12-11 12:36
*/
@Data
public class OrderReq {
private String orderId;
private String userId;
}
- 以上只是一个demo,实际的支付还要考虑订单的容错机制,超时和异常订单处理;有建议的可以提出建议,一起探讨一下!