修复:收口下单防重与成功提示

This commit is contained in:
xiaowang
2026-04-03 11:44:32 +08:00
parent 9cadc23872
commit eb1c209d79
6 changed files with 1346 additions and 16 deletions
@@ -15,4 +15,21 @@ public interface CartMapper extends BaseMapper<CartDO> {
@Select("SELECT * FROM t_cart WHERE user_id = #{userId} AND product_id = #{productId} AND is_delete = 0")
CartDO selectByUserIdAndProductId(@Param("userId") Long userId, @Param("productId") Long productId);
@Select({
"<script>",
"SELECT * FROM t_cart",
"WHERE user_id = #{userId}",
"AND is_delete = 0",
"AND product_id IN",
"<foreach collection='productIds' item='productId' open='(' separator=',' close=')'>",
"#{productId}",
"</foreach>",
"FOR UPDATE",
"</script>"
})
List<CartDO> selectByUserIdAndProductIdsForUpdate(
@Param("userId") Long userId,
@Param("productIds") List<Long> productIds
);
}
@@ -28,11 +28,17 @@ import com.xiaowang.yuminailcore.vo.OrderItemVO;
import com.xiaowang.yuminailcore.vo.OrderVO;
import com.xiaowang.yuminailcore.vo.TagVO;
import com.xiaowang.yuminailcore.vo.UserCouponVO;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.util.StringUtils;
import javax.annotation.Resource;
import javax.annotation.PreDestroy;
import java.math.BigDecimal;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
@@ -40,13 +46,20 @@ import java.time.format.DateTimeParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
@Service
public class OrderServiceImpl implements OrderService {
@@ -56,6 +69,13 @@ public class OrderServiceImpl implements OrderService {
private static final String COUPON_SOURCE_NONE = "NONE";
private static final String COUPON_SOURCE_USER = "USER_COUPON";
private static final String COUPON_SOURCE_SYSTEM_VIP = "SYSTEM_VIP";
private static final String ORDER_CREATE_USER_LOCK_PREFIX = "order:create:user:";
private static final String ORDER_CREATE_ARTIST_LOCK_PREFIX = "order:create:artist:";
private static final Duration ORDER_CREATE_LOCK_TTL = Duration.ofSeconds(15);
private static final long ORDER_CREATE_LOCK_TTL_MILLIS = ORDER_CREATE_LOCK_TTL.toMillis();
private static final long ORDER_CREATE_LOCK_RENEW_INTERVAL_MILLIS = 5000L;
private static final long ARTIST_LOCK_RETRY_INTERVAL_MILLIS = 150L;
private static final long ARTIST_LOCK_WAIT_TIMEOUT_MILLIS = 1500L;
private static final List<DateTimeFormatter> APPOINTMENT_INPUT_FORMATTERS = Arrays.asList(
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"),
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"),
@@ -65,6 +85,25 @@ public class OrderServiceImpl implements OrderService {
private static final Pattern DURATION_PATTERN = Pattern.compile("(\\d+)");
private static final Pattern BUSINESS_HOURS_PATTERN = Pattern.compile("^(\\d{1,2}:\\d{2})\\s*[-~至]\\s*(\\d{1,2}:\\d{2})$");
private static final long DEFAULT_SERVICE_DURATION_MINUTES = 60L;
private static final DefaultRedisScript<Long> RELEASE_LOCK_SCRIPT = new DefaultRedisScript<>();
private static final DefaultRedisScript<Long> RENEW_LOCK_SCRIPT = new DefaultRedisScript<>();
private static final ScheduledExecutorService LOCK_RENEW_EXECUTOR = Executors.newSingleThreadScheduledExecutor(new LockRenewThreadFactory());
static {
RELEASE_LOCK_SCRIPT.setScriptText(
"if redis.call('get', KEYS[1]) == ARGV[1] then " +
"return redis.call('del', KEYS[1]) " +
"else return 0 end"
);
RELEASE_LOCK_SCRIPT.setResultType(Long.class);
RENEW_LOCK_SCRIPT.setScriptText(
"if redis.call('get', KEYS[1]) == ARGV[1] then " +
"return redis.call('pexpire', KEYS[1], ARGV[2]) " +
"else return 0 end"
);
RENEW_LOCK_SCRIPT.setResultType(Long.class);
}
@Resource
private OrderMapper orderMapper;
@@ -102,13 +141,62 @@ public class OrderServiceImpl implements OrderService {
@Resource
private TimeOrderedSnowflakeIdGenerator snowflakeIdGenerator;
@Resource
private StringRedisTemplate stringRedisTemplate;
@Resource
private TransactionTemplate transactionTemplate;
@PreDestroy
public void shutdownOrderLockRenewExecutor() {
LOCK_RENEW_EXECUTOR.shutdownNow();
}
@Override
@Transactional
public OrderVO createOrder(Long userId, OrderDTO orderDTO) {
if (orderDTO == null || orderDTO.getItems() == null || orderDTO.getItems().isEmpty()) {
throw new RuntimeException("订单项不能为空");
}
String userLockKey = ORDER_CREATE_USER_LOCK_PREFIX + userId;
String userLockToken = UUID.randomUUID().toString();
if (!tryAcquireOrderLock(userLockKey, userLockToken)) {
throw new RuntimeException("订单正在提交中,请勿重复点击");
}
LockLease userLockLease = startOrderLockRenewal(userLockKey, userLockToken);
String artistLockKey = null;
String artistLockToken = null;
LockLease artistLockLease = null;
try {
Long artistId = resolveRequestedArtistId(orderDTO.getItems());
artistLockKey = ORDER_CREATE_ARTIST_LOCK_PREFIX + artistId;
artistLockToken = UUID.randomUUID().toString();
if (!tryAcquireArtistOrderLock(artistLockKey, artistLockToken)) {
throw new RuntimeException("当前美甲师预约繁忙,请稍后再试");
}
artistLockLease = startOrderLockRenewal(artistLockKey, artistLockToken);
OrderVO orderVO = transactionTemplate.execute(status -> createOrderInTransaction(userId, orderDTO));
if (orderVO == null) {
throw new RuntimeException("订单创建失败,请稍后重试");
}
return orderVO;
} finally {
stopOrderLockRenewal(artistLockLease);
releaseOrderLock(artistLockKey, artistLockToken);
stopOrderLockRenewal(userLockLease);
releaseOrderLock(userLockKey, userLockToken);
}
}
private OrderVO createOrderInTransaction(Long userId, OrderDTO orderDTO) {
if (orderDTO == null || orderDTO.getItems() == null || orderDTO.getItems().isEmpty()) {
throw new RuntimeException("订单项不能为空");
}
List<OrderItemDTO> orderItemDTOs = orderDTO.getItems();
BigDecimal totalAmount = BigDecimal.ZERO;
List<OrderItemDO> orderItems = new ArrayList<>();
@@ -118,6 +206,9 @@ public class OrderServiceImpl implements OrderService {
Set<String> selectedTagNames = new LinkedHashSet<>();
Long shopId = null;
Long selectedArtistId = null;
Map<Long, Integer> requestedQuantityByProductId = buildRequestedQuantityMap(orderItemDTOs);
List<Long> requestedProductIds = new ArrayList<>(requestedQuantityByProductId.keySet());
Map<Long, CartDO> lockedCartItemMap = loadLockedCartItems(userId, requestedProductIds);
for (OrderItemDTO orderItemDTO : orderItemDTOs) {
validateOrderQuantity(orderItemDTO.getQuantity());
@@ -128,11 +219,12 @@ public class OrderServiceImpl implements OrderService {
}
productCache.put(product.getId(), product);
CartDO cartItem = cartMapper.selectByUserIdAndProductId(userId, orderItemDTO.getProductId());
CartDO cartItem = lockedCartItemMap.get(orderItemDTO.getProductId());
if (cartItem == null) {
throw new RuntimeException("请先将商品加入购物车后再结算");
}
if (cartItem.getQuantity() == null || cartItem.getQuantity() < orderItemDTO.getQuantity()) {
Integer requestedQuantity = requestedQuantityByProductId.get(orderItemDTO.getProductId());
if (cartItem.getQuantity() == null || requestedQuantity == null || cartItem.getQuantity() < requestedQuantity) {
throw new RuntimeException("购物车中的商品数量已变化,请刷新后重试");
}
@@ -140,6 +232,7 @@ public class OrderServiceImpl implements OrderService {
if (shopId == null) {
shopId = product.getShopId();
validateUserCanCreateOrderInShop(userId, shopId);
} else if (!shopId.equals(product.getShopId())) {
throw new RuntimeException("跨店铺商品请分开下单");
}
@@ -237,13 +330,11 @@ public class OrderServiceImpl implements OrderService {
orderItemMapper.insert(item);
}
for (OrderItemDTO orderItemDTO : orderItemDTOs) {
QueryWrapper<CartDO> cartWrapper = new QueryWrapper<>();
cartWrapper.eq("user_id", userId)
.eq("product_id", orderItemDTO.getProductId())
.eq("is_delete", 0);
cartMapper.delete(cartWrapper);
}
QueryWrapper<CartDO> cartWrapper = new QueryWrapper<>();
cartWrapper.eq("user_id", userId)
.eq("is_delete", 0)
.in("product_id", requestedProductIds);
cartMapper.delete(cartWrapper);
return buildOrderVO(order);
}
@@ -368,6 +459,7 @@ public class OrderServiceImpl implements OrderService {
private OrderVO buildOrderVO(OrderDO order, Long artistIdFilter) {
OrderVO orderVO = new OrderVO();
Map<Long, UserDO> userCache = new HashMap<>();
orderVO.setId(order.getId());
orderVO.setOrderNo(order.getOrderNo());
orderVO.setUserId(order.getUserId());
@@ -377,6 +469,9 @@ public class OrderServiceImpl implements OrderService {
orderVO.setCouponId(order.getCouponId());
orderVO.setUserCouponId(order.getUserCouponId());
orderVO.setCouponSourceType(order.getCouponSourceType());
UserDO customer = getUserFromCache(order.getUserId(), userCache);
orderVO.setCustomerNickname(resolveCustomerNickname(customer));
orderVO.setCustomerPhoneMasked(maskPhone(customer == null ? null : customer.getPhone()));
orderVO.setStatus(order.getStatus());
switch (order.getStatus()) {
@@ -438,7 +533,7 @@ public class OrderServiceImpl implements OrderService {
if (item.getArtistId() != null) {
itemVO.setArtistId(item.getArtistId());
UserDO artist = userMapper.selectById(item.getArtistId());
UserDO artist = getUserFromCache(item.getArtistId(), userCache);
if (artist != null) {
itemVO.setArtistName(artist.getNickname());
itemVO.setArtistAvatar(artist.getAvatar());
@@ -456,6 +551,171 @@ public class OrderServiceImpl implements OrderService {
return orderVO;
}
private Map<Long, Integer> buildRequestedQuantityMap(List<OrderItemDTO> orderItemDTOs) {
Map<Long, Integer> requestedQuantityByProductId = new HashMap<>();
for (OrderItemDTO orderItemDTO : orderItemDTOs) {
if (orderItemDTO == null || orderItemDTO.getProductId() == null) {
throw new RuntimeException("订单商品信息不完整");
}
requestedQuantityByProductId.merge(
orderItemDTO.getProductId(),
orderItemDTO.getQuantity() == null ? 0 : orderItemDTO.getQuantity(),
Integer::sum
);
}
return requestedQuantityByProductId;
}
private Map<Long, CartDO> loadLockedCartItems(Long userId, List<Long> requestedProductIds) {
if (requestedProductIds == null || requestedProductIds.isEmpty()) {
return Collections.emptyMap();
}
List<CartDO> lockedCartItems = cartMapper.selectByUserIdAndProductIdsForUpdate(userId, requestedProductIds);
Map<Long, CartDO> lockedCartItemMap = new HashMap<>();
for (CartDO cartDO : lockedCartItems) {
if (cartDO != null && cartDO.getProductId() != null) {
lockedCartItemMap.put(cartDO.getProductId(), cartDO);
}
}
return lockedCartItemMap;
}
private void validateUserCanCreateOrderInShop(Long userId, Long shopId) {
if (!userShopBindingSupport.canUserAccessShop(userId, shopId, false, null)) {
throw new RuntimeException("当前账号已不可在该店铺下单,请切换门店后重试");
}
}
private Long resolveRequestedArtistId(List<OrderItemDTO> orderItemDTOs) {
Long artistId = null;
for (OrderItemDTO orderItemDTO : orderItemDTOs) {
if (orderItemDTO == null || orderItemDTO.getArtistId() == null) {
throw new RuntimeException("请为每个商品选择美甲师");
}
if (artistId == null) {
artistId = orderItemDTO.getArtistId();
continue;
}
if (!artistId.equals(orderItemDTO.getArtistId())) {
throw new RuntimeException("不同美甲师的项目请分开下单");
}
}
if (artistId == null) {
throw new RuntimeException("请为每个商品选择美甲师");
}
return artistId;
}
private boolean tryAcquireOrderLock(String lockKey, String lockToken) {
return Boolean.TRUE.equals(
stringRedisTemplate.opsForValue().setIfAbsent(lockKey, lockToken, ORDER_CREATE_LOCK_TTL)
);
}
private boolean tryAcquireArtistOrderLock(String lockKey, String lockToken) {
long deadline = System.currentTimeMillis() + ARTIST_LOCK_WAIT_TIMEOUT_MILLIS;
while (System.currentTimeMillis() <= deadline) {
if (tryAcquireOrderLock(lockKey, lockToken)) {
return true;
}
try {
Thread.sleep(ARTIST_LOCK_RETRY_INTERVAL_MILLIS);
} catch (InterruptedException exception) {
Thread.currentThread().interrupt();
return false;
}
}
return false;
}
// 慢事务期间持续续租,避免下单锁在事务未完成时提前过期。
private LockLease startOrderLockRenewal(String lockKey, String lockToken) {
if (!StringUtils.hasText(lockKey) || !StringUtils.hasText(lockToken)) {
return null;
}
LockLease lockLease = new LockLease(lockKey, lockToken);
ScheduledFuture<?> future = LOCK_RENEW_EXECUTOR.scheduleWithFixedDelay(
() -> renewOrderLock(lockLease),
ORDER_CREATE_LOCK_RENEW_INTERVAL_MILLIS,
ORDER_CREATE_LOCK_RENEW_INTERVAL_MILLIS,
TimeUnit.MILLISECONDS
);
lockLease.attachFuture(future);
return lockLease;
}
private void renewOrderLock(LockLease lockLease) {
if (lockLease == null || !lockLease.isActive()) {
return;
}
try {
Long renewResult = stringRedisTemplate.execute(
RENEW_LOCK_SCRIPT,
Collections.singletonList(lockLease.getLockKey()),
lockLease.getLockToken(),
String.valueOf(ORDER_CREATE_LOCK_TTL_MILLIS)
);
if (!Long.valueOf(1L).equals(renewResult)) {
lockLease.cancel();
}
} catch (Exception ignored) {
}
}
private void stopOrderLockRenewal(LockLease lockLease) {
if (lockLease == null) {
return;
}
lockLease.cancel();
}
private void releaseOrderLock(String lockKey, String lockToken) {
if (!StringUtils.hasText(lockKey) || !StringUtils.hasText(lockToken)) {
return;
}
stringRedisTemplate.execute(RELEASE_LOCK_SCRIPT, Collections.singletonList(lockKey), lockToken);
}
private UserDO getUserFromCache(Long userId, Map<Long, UserDO> userCache) {
if (userId == null) {
return null;
}
if (userCache.containsKey(userId)) {
return userCache.get(userId);
}
UserDO userDO = userMapper.selectById(userId);
userCache.put(userId, userDO);
return userDO;
}
private String resolveCustomerNickname(UserDO customer) {
if (customer == null) {
return "用户";
}
if (StringUtils.hasText(customer.getNickname())) {
return customer.getNickname();
}
if (StringUtils.hasText(customer.getAccount())) {
return customer.getAccount();
}
return "用户";
}
private String maskPhone(String phone) {
if (!StringUtils.hasText(phone)) {
return null;
}
String normalizedPhone = phone.trim();
if (normalizedPhone.length() < 7) {
return normalizedPhone;
}
return normalizedPhone.substring(0, 3)
+ "****"
+ normalizedPhone.substring(normalizedPhone.length() - 4);
}
private void validateOrderQuantity(Integer quantity) {
if (quantity == null || quantity < 1) {
throw new RuntimeException("订单商品数量必须大于 0");
@@ -805,6 +1065,54 @@ public class OrderServiceImpl implements OrderService {
couponMapper.updateById(couponDO);
}
private static final class LockLease {
private final String lockKey;
private final String lockToken;
private volatile ScheduledFuture<?> future;
private volatile boolean active = true;
private LockLease(String lockKey, String lockToken) {
this.lockKey = lockKey;
this.lockToken = lockToken;
}
private String getLockKey() {
return lockKey;
}
private String getLockToken() {
return lockToken;
}
private boolean isActive() {
return active;
}
private void attachFuture(ScheduledFuture<?> future) {
this.future = future;
if (!active && future != null) {
future.cancel(false);
}
}
private void cancel() {
active = false;
ScheduledFuture<?> currentFuture = future;
if (currentFuture != null) {
currentFuture.cancel(false);
}
}
}
private static final class LockRenewThreadFactory implements ThreadFactory {
@Override
public Thread newThread(Runnable runnable) {
Thread thread = new Thread(runnable, "order-lock-renew");
thread.setDaemon(true);
return thread;
}
}
private static final class CouponSelection {
private final String sourceType;
private final Long couponId;
@@ -18,6 +18,8 @@ public class OrderVO {
private Long userCouponId;
private String couponSourceType;
private String couponName;
private String customerNickname;
private String customerPhoneMasked;
private Integer status;
private String statusText;
private LocalDateTime createTime;