Commit e33fb70c authored by gaoyingwei's avatar gaoyingwei

修改 定时

parent bc9e1526
......@@ -29,6 +29,7 @@ import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
......@@ -37,6 +38,9 @@ import org.rcisoft.core.model.CyPageInfo;
import java.io.IOException;
import java.math.BigDecimal;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
......@@ -1025,4 +1029,599 @@ public class CmsOrderServiceImpl extends ServiceImpl<CmsOrderRepository,CmsOrder
}
}
//redis订单落库
@Transactional
public void executeInsertOrder() throws NoSuchAlgorithmException {
// 查询 【order:activity:${所有}:${所有}】
Set<String> map = redisTemplate.keys(RedisCons.ORDER_ACTIVITY+"*");
if (CollectionUtils.isNotEmpty(map)) {
List<String>list = new ArrayList<>(map);
if (list.size()>50){
//过滤【随机】50条,【未同步】
Random sc = SecureRandom.getInstanceStrong();
for (int i = 0; i < 50; i++) {
// 随机一个索引
String key = list.get(sc.nextInt(list.size()));
insertOrder(key);
}
} else {
for (String key : list) {
insertOrder(key);
}
}
}
}
private void insertOrder(String key) {
Object detail = cyRedisServiceImpl.get(key);
CmsOrder orderDetail = JSON.parseObject(JSON.toJSONString(detail), CmsOrder.class);
if (orderDetail.getState().equals(0)){
//加redis锁 循环 redisson key:【order:db:${oid}】
boolean isGetLock = false;
RLock lock = redissonClient.getLock(RedisCons.ORDER_DB + orderDetail.getBusinessId());
try {
isGetLock = lock.tryLock(Long.parseLong(RedisCons.ORDER_INFO_LOCK_WAIT_TIME),
Long.parseLong(RedisCons.ORDER_INFO_LOCK_LEASE_TIME), TimeUnit.SECONDS);
if (isGetLock) {
//查询DB -> 是否已落库
CmsOrder info = baseMapper.selectById(orderDetail.getBusinessId());
//未落库->落库;redis key: 【order:activity:${aid}:${oid}】【未同步】 => 落库
if (info == null) {
baseMapper.insert(orderDetail);
//添加报名信息
CmsApplication application = new CmsApplication();
application.setUserId(orderDetail.getUserId());
application.setActivityId(orderDetail.getGoodsId());
application.setName(orderDetail.getAccount());
// application.setPhone(orderDetail.get);
//0 待支付 1已取消 2退款中 3退款中 4后台退款中 5后台退款中 6退款完成 7后台退款完成 8支付中 9 支付完成 10订单关闭
// if (orderDetail.getStatus().equals(0)||orderDetail.getStatus().equals(2)||orderDetail.getStatus().equals(3)||orderDetail.getStatus().equals(4)||
// orderDetail.getStatus().equals(5)||orderDetail.getStatus().equals(8)||orderDetail.getStatus().equals(9))
// application.setStatus("1");
// else if (orderDetail.getStatus().equals(1)||orderDetail.getStatus().equals(10))
// application.setStatus("2");
// else if (orderDetail.getStatus().equals(6)||orderDetail.getStatus().equals(7))
// application.setStatus("3");
application.setStatus(orderDetail.getApplicationStatus());
application.setApplicationFee(orderDetail.getPayPrice());
application.setOrderId(orderDetail.getBusinessId());
applicationRepository.insert(application);
// //如果有优惠券,进行核销
// if (orderDetail.getCouponId() != null) {
// UserCouponRelative userCouponRelative = new UserCouponRelative();
// userCouponRelative.setBusinessId(orderDetail.getCouponId());
// userCouponRelative.setCancelId(orderDetail.getStoreId());
// userCouponRelative.setOrderId(orderDetail.getBusinessId());
// userCouponRelative.setStatus(1);
// userCouponRelative.setCancelTime(new Date());
// couponInfoRepository.useCouponById(userCouponRelative);
// }
//加订单redis锁
RLock redisLock = redissonClient.getLock(RedisCons.ORDER_REDIS + orderDetail.getBusinessId());
try {
isGetLock = redisLock.tryLock(Long.parseLong(RedisCons.ORDER_INFO_LOCK_WAIT_TIME),
Long.parseLong(RedisCons.ORDER_INFO_LOCK_LEASE_TIME), TimeUnit.SECONDS);
if (isGetLock) {
//redis key: 【order:activity:${aid}:${oid}】 value 【hash】;ttl:-1;hash state-> 【已同步】
orderDetail.setState(1);
cyRedisServiceImpl.set(RedisCons.ORDER_ACTIVITY +":"+ orderDetail.getGoodsId() + ":" + orderDetail.getBusinessId(),orderDetail);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
isGetLock = false;
} finally {
redisLock.unlock();
log.error("释放成功");
}
} else {
//0 待支付 1已取消 2退款中 3退款中 4后台退款中 5后台退款中 6退款完成 7后台退款完成 8支付中 9 支付完成 10订单关闭
switch (orderDetail.getStatus()) {
case 0 ->//待支付
orderUpdateSatusExecute(orderDetail);
case 1 ->//1已取消
orderCancelExecute(orderDetail);
case 2 ->//2退款中
orderUpdateSatusExecute(orderDetail);
case 3 ->//3退款中
orderUpdateSatusExecute(orderDetail);
case 4 ->//4后台退款中
orderUpdateSatusExecute(orderDetail);
case 5 ->//5后台退款中
orderUpdateSatusExecute(orderDetail);
case 6 ->//6退款完成
orderUpdateSatusExecute(orderDetail);
case 7 ->//7后台退款完成
orderUpdateSatusExecute(orderDetail);
case 8 ->//8支付中
orderUpdateSatusExecute(orderDetail);
case 9 ->//支付完成
orderFinishExecute(orderDetail);
case 11 ->//11已核销
orderUpdateSatusExecute(orderDetail);
default -> {
}
}
}
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
isGetLock = false;
} finally {
lock.unlock();
log.error("释放成功");
}
}
}
//支付完成
private void orderFinishExecute(CmsOrder orderDetail) {
boolean isGetLock = false;
orderDetail.setUpdateDate(new Date());
baseMapper.updateById(orderDetail);
CmsApplication application = applicationRepository.selectByOrderId(orderDetail.getBusinessId());
application.setStatus(orderDetail.getApplicationStatus());
applicationRepository.updateById(application);
//积分计算
// BigDecimal price = orderDetail.getPayPrice();
// IntegralAmountRelative relative = integralAmountRelativeRepository.queryIntegralByPrice(price);
// if (relative != null) {
// //查询会员信息
// SysUser info = sysUserRepositorys.selectUserById(orderDetail.getUserId());
// UserIntegral userIntegral = new UserIntegral();
// userIntegral.setUserId(orderDetail.getUserId());
// userIntegral.setGoodsId(orderDetail.getGoodsId());
// userIntegral.setChange(relative.getIntegral());
// Integer integral = info.getIntegral() + relative.getIntegral();
// userIntegral.setIntegral(integral);
// userIntegral.setCreateBy(String.valueOf(orderDetail.getUserId()));
// userIntegral.setCreateTime(new Date());
// userIntegralRepository.insertUserIntegral(userIntegral);
// //会员等级计算
// MemberBenefits benefits = memberBenefitsRepository.selectMemberBenefitsByLevel(info.getLevel()+1);
// if (benefits != null && (integral >= benefits.getIntegral())) {
// info.setLevel(info.getLevel()+1);
// }
// info.setIntegral(integral);
// sysUserRepositorys.updateSysUser(info);
// cyRedisServiceImpl.set(RedisCons.MEMBER_INFO + ":" + orderDetail.getUserId(), info);
// }
//加订单redis锁
RLock redisLock = redissonClient.getLock(RedisCons.ORDER_REDIS + orderDetail.getBusinessId());
try {
isGetLock = redisLock.tryLock(Long.parseLong(RedisCons.ORDER_INFO_LOCK_WAIT_TIME),
Long.parseLong(RedisCons.ORDER_INFO_LOCK_LEASE_TIME), TimeUnit.SECONDS);
if (isGetLock) {
//redis key: 【order:activity:${aid}:${oid}】 value 【hash】;ttl:-1;hash state-> 【已同步】
orderDetail.setState(1);
cyRedisServiceImpl.set(RedisCons.ORDER_ACTIVITY +":"+ orderDetail.getGoodsId() + ":" + orderDetail.getBusinessId(),orderDetail);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
isGetLock = false;
} finally {
redisLock.unlock();
log.error("释放成功");
}
}
//订单状态改为支付中
private void orderUpdateSatusExecute(CmsOrder orderDetail) {
boolean isGetLock = false;
orderDetail.setUpdateDate(new Date());
baseMapper.updateById(orderDetail);
CmsApplication application = applicationRepository.selectByOrderId(orderDetail.getBusinessId());
application.setStatus(orderDetail.getApplicationStatus());
applicationRepository.updateById(application);
//加订单redis锁
RLock redisLock = redissonClient.getLock(RedisCons.ORDER_REDIS + orderDetail.getBusinessId());
try {
isGetLock = redisLock.tryLock(Long.parseLong(RedisCons.ORDER_INFO_LOCK_WAIT_TIME),
Long.parseLong(RedisCons.ORDER_INFO_LOCK_LEASE_TIME), TimeUnit.SECONDS);
if (isGetLock) {
//redis key: 【order:activity:${aid}:${oid}】 value 【hash】;ttl:-1;hash state-> 【已同步】
orderDetail.setState(1);
cyRedisServiceImpl.set(RedisCons.ORDER_ACTIVITY +":"+ orderDetail.getGoodsId() + ":" + orderDetail.getBusinessId(),orderDetail);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
isGetLock = false;
} finally {
redisLock.unlock();
log.error("释放成功");
}
}
//订单状态改为已取消
private void orderCancelExecute(CmsOrder orderDetail) {
boolean isGetLock = false;
orderDetail.setUpdateDate(new Date());
baseMapper.updateById(orderDetail);
CmsApplication application = applicationRepository.selectByOrderId(orderDetail.getBusinessId());
application.setStatus(orderDetail.getApplicationStatus());
applicationRepository.updateById(application);
//订单优惠券退还
// if (orderDetail.getCouponId() != null) {
// UserCouponRelative userCouponRelative = new UserCouponRelative();
// userCouponRelative.setBusinessId(orderDetail.getCouponId());
// userCouponRelative.setStatus(0);
// couponInfoRepository.cancelCouponById(userCouponRelative);
// }
//加订单redis锁
RLock redisLock = redissonClient.getLock(RedisCons.ORDER_REDIS + orderDetail.getBusinessId());
try {
isGetLock = redisLock.tryLock(Long.parseLong(RedisCons.ORDER_INFO_LOCK_WAIT_TIME),
Long.parseLong(RedisCons.ORDER_INFO_LOCK_LEASE_TIME), TimeUnit.SECONDS);
if (isGetLock) {
//redis key: 【order:activity:${aid}:${oid}】 value 【hash】;ttl:-1;hash state-> 【已同步】
orderDetail.setState(1);
cyRedisServiceImpl.set(RedisCons.ORDER_ACTIVITY +":"+ orderDetail.getGoodsId() + ":" + orderDetail.getBusinessId(),orderDetail);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
isGetLock = false;
} finally {
redisLock.unlock();
log.error("释放成功");
}
}
//redis订单关闭
@Transactional
public void executeCloseOrder() throws NoSuchAlgorithmException {
// 查询 【order:activity:${所有}:${所有}】
Set<String> map = redisTemplate.keys(RedisCons.ORDER_ACTIVITY+"*");
if (CollectionUtils.isNotEmpty(map)) {
List<String>list = new ArrayList<>(map);
if (list.size()>50){
//过滤【随机】50条,state -> 待支付,大于30min
Random sc = SecureRandom.getInstanceStrong();
for (int i = 0; i < 50; i++) {
// 随机一个索引
String key = list.get(sc.nextInt(list.size()));
closeOrder(key);
}
} else {
for (String key : list) {
closeOrder(key);
}
}
}
}
private void closeOrder(String key) {
Object detail = cyRedisServiceImpl.get(key);
CmsOrder orderDetail = JSON.parseObject(JSON.toJSONString(detail), CmsOrder.class);
//status -> 待支付,大于30min
Date orderTime = orderDetail.getCreateDate();
Date a = new Date();
if (orderDetail.getStatus().equals(0) && a.getTime()-orderTime.getTime() > 1800000){
//加redis锁
boolean isGetLock = false;
RLock lock = redissonClient.getLock(RedisCons.ORDER_DB + orderDetail.getBusinessId());
try {
isGetLock = lock.tryLock(Long.parseLong(RedisCons.ORDER_INFO_LOCK_WAIT_TIME),
Long.parseLong(RedisCons.ORDER_INFO_LOCK_LEASE_TIME), TimeUnit.SECONDS);
if (isGetLock) {
// redis key: 【order:activity:${oid}】 value 【hash】;hash state 是否是 【待支付
orderDetail.setStatus(10);
orderDetail.setUpdateDate(new Date());
//查询DB -> 是否已落库
CmsOrder info = baseMapper.selectById(orderDetail.getBusinessId());
if (info != null) {
baseMapper.updateById(orderDetail);
CmsApplication application = applicationRepository.selectByOrderId(orderDetail.getBusinessId());
application.setStatus("2");
applicationRepository.updateById(application);
} else {
baseMapper.insert(orderDetail);
//添加报名信息
CmsApplication application = new CmsApplication();
application.setUserId(orderDetail.getUserId());
application.setActivityId(orderDetail.getGoodsId());
application.setName(orderDetail.getAccount());
// application.setPhone(orderDetail.get);
//0 待支付 1已取消 2退款中 3退款中 4后台退款中 5后台退款中 6退款完成 7后台退款完成 8支付中 9 支付完成 10订单关闭
// if (orderDetail.getStatus().equals(0)||orderDetail.getStatus().equals(2)||orderDetail.getStatus().equals(3)||orderDetail.getStatus().equals(4)||
// orderDetail.getStatus().equals(5)||orderDetail.getStatus().equals(8)||orderDetail.getStatus().equals(9))
// application.setStatus("1");
// else if (orderDetail.getStatus().equals(1)||orderDetail.getStatus().equals(10))
// application.setStatus("2");
// else if (orderDetail.getStatus().equals(6)||orderDetail.getStatus().equals(7))
// application.setStatus("3");
application.setStatus("2");
application.setApplicationFee(orderDetail.getPayPrice());
application.setOrderId(orderDetail.getBusinessId());
applicationRepository.insert(application);
}
//如果使用了优惠券,则改为未使用
// if (orderDetail.getCouponId() != null) {
// UserCouponRelative userCouponRelative = new UserCouponRelative();
// userCouponRelative.setBusinessId(orderDetail.getCouponId());
// userCouponRelative.setStatus(0);
// couponInfoRepository.cancelCouponById(userCouponRelative);
// }
//加订单redis锁
RLock redisLock = redissonClient.getLock(RedisCons.ORDER_REDIS + orderDetail.getBusinessId());
try {
isGetLock = redisLock.tryLock(Long.parseLong(RedisCons.ORDER_INFO_LOCK_WAIT_TIME),
Long.parseLong(RedisCons.ORDER_INFO_LOCK_LEASE_TIME), TimeUnit.SECONDS);
if (isGetLock) {
//redis key: 【order:activity:${aid}:${oid}】 value 【hash】;ttl:-1;hash state-> 【已同步】
orderDetail.setState(1);
cyRedisServiceImpl.set(RedisCons.ORDER_ACTIVITY +":"+ orderDetail.getGoodsId() + ":" + orderDetail.getBusinessId(),orderDetail);
//退人数
// ActivityInfo activityInfo = activityInfoRepository.selectActivityInfoById(orderDetail.getGoodsId());
// if (activityInfo.getIsRestrictions().equals(0))
stockService.addStock(RedisCons.ACTIVITY_COUNT +":"+ orderDetail.getGoodsId(), 1);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
isGetLock = false;
} finally {
redisLock.unlock();
log.error("释放成功");
}
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
isGetLock = false;
} finally {
lock.unlock();
log.error("释放成功");
}
}
}
//支付确认补救
@Transactional
public void executePayOrder() throws IOException, JDOMException {
// 查询DB进行中的活动订单,支付中,前50条
QueryWrapper<CmsOrder> wrapper = new QueryWrapper<>();
wrapper.eq("status",8);
wrapper.eq("type",1);
wrapper.eq("del_flag",0);
wrapper.orderByAsc("order_time");
wrapper.last("limit 50");
List<CmsOrder> orderInfoList = baseMapper.selectList(wrapper);
for (CmsOrder orderInfo : orderInfoList) {
//主动查询订单状态
String status = wxPayService.selectWxOrderStatus(String.valueOf(orderInfo.getBusinessId()));
switch (status) {
case "SUCCESS" -> { //支付成功
log.info("SUCCESS--支付成功");
//加订单redis锁
boolean isGetLock = false;
RLock redisLock = redissonClient.getLock(RedisCons.ORDER_REDIS + orderInfo.getBusinessId());
try {
isGetLock = redisLock.tryLock(Long.parseLong(RedisCons.ORDER_INFO_LOCK_WAIT_TIME),
Long.parseLong(RedisCons.ORDER_INFO_LOCK_LEASE_TIME), TimeUnit.SECONDS);
if (isGetLock) {
Object detail = cyRedisServiceImpl.get(RedisCons.ORDER_ACTIVITY + ":" + orderInfo.getGoodsId() + ":" + orderInfo.getBusinessId());
if (detail != null) {
CmsOrder orderDetail = JSON.parseObject(JSON.toJSONString(detail), CmsOrder.class);
orderDetail.setState(0);
orderDetail.setStatus(9);
orderDetail.setApplicationStatus("1");
//redis key: 【order:activity:${aid}:${oid}】 value 【hash】;ttl:-1;hash state-> 【未同步】,status -> 支付完成
cyRedisServiceImpl.set(RedisCons.ORDER_ACTIVITY + ":" + orderDetail.getGoodsId() + ":" + orderDetail.getBusinessId(), orderDetail);
//发送 mq,exchange:`order_activity` route-key:`order_activity_status` value 【订单】
// rabbitClusterUtil.sendMsg(orderDetail, rabbitMQConfigBean.ORDER_EXCHANGE_NAME, rabbitMQConfigBean.ORDER_STATUS_QUEUE_NAME);
}
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
isGetLock = false;
} finally {
redisLock.unlock();
log.error("释放成功");
}
}
case "REFUND" -> //转入退款
log.info("REFUND--转入退款");
case "NOTPAY" -> //未支付
log.info("NOTPAY--未支付");
case "CLOSED" -> //已关闭
log.info("CLOSED--已关闭");
case "REVOKED" -> //已撤销(刷卡支付)
log.info("REVOKED--已撤销(刷卡支付)");
case "USERPAYING" -> //用户支付中
log.info("USERPAYING--用户支付中");
case "PAYERROR" -> {//支付失败(其他原因,如银行返回失败)
log.info("PAYERROR--支付失败(其他原因,如银行返回失败)");
//加订单redis锁
boolean isGetLock = false;
RLock redisLock = redissonClient.getLock(RedisCons.ORDER_REDIS + orderInfo.getBusinessId());
try {
isGetLock = redisLock.tryLock(Long.parseLong(RedisCons.ORDER_INFO_LOCK_WAIT_TIME),
Long.parseLong(RedisCons.ORDER_INFO_LOCK_LEASE_TIME), TimeUnit.SECONDS);
if (isGetLock) {
Object detail = cyRedisServiceImpl.get(RedisCons.ORDER_ACTIVITY +":"+ orderInfo.getGoodsId() +":"+ orderInfo.getBusinessId());
if (detail!=null) {
CmsOrder orderDetail = JSON.parseObject(JSON.toJSONString(detail), CmsOrder.class);
//redis key: 【order:activity:${aid}:${oid}】 value 【hash】;ttl:-1;hash state-> 【未同步】,status -> 待支付
orderDetail.setState(0);
orderDetail.setStatus(0);
orderDetail.setApplicationStatus("1");
cyRedisServiceImpl.set(RedisCons.ORDER_ACTIVITY +":"+ orderDetail.getGoodsId() + ":" + orderDetail.getBusinessId(),orderDetail);
//发送 mq,exchange:`order_activity` route-key:`order_activity_status` value 【订单】
// rabbitClusterUtil.sendMsg(orderDetail, rabbitMQConfigBean.ORDER_EXCHANGE_NAME,rabbitMQConfigBean.ORDER_STATUS_QUEUE_NAME);
} else
throw new CyServiceException("订单支付失败,请稍后再试");
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
isGetLock = false;
} finally {
redisLock.unlock();
log.error("释放成功");
}
}
case "ACCEPT" -> //已接收,等待扣款
log.info("ACCEPT--已接收,等待扣款");
default ->
log.info("订单状态查询失败");
}
}
}
//任务:退款接口调用补救
@Transactional
public void executeRefundOrder() {
// 查询DB进行中的活动订单,退款中(3 5),退款接口调用失败1,2,前50条
QueryWrapper<CmsOrder> wrapper = new QueryWrapper<>();
wrapper.in("status",3,5);
wrapper.eq("type",1);
wrapper.eq("del_flag",0);
wrapper.in("refund_count",1,2);
wrapper.orderByAsc("refund_time");
wrapper.last("limit 50");
List<CmsOrder> orderInfoList = baseMapper.selectList(wrapper);
for (CmsOrder orderInfo : orderInfoList) {
//调用退款接口
String result = wxPayService.refundOrder(orderInfo);
//redisson key:【order:redis:${oid}】
boolean isGetLock = false;
RLock redisLock = redissonClient.getLock(RedisCons.ORDER_REDIS + orderInfo.getBusinessId());
try {
isGetLock = redisLock.tryLock(Long.parseLong(RedisCons.ORDER_INFO_LOCK_WAIT_TIME),
Long.parseLong(RedisCons.ORDER_INFO_LOCK_LEASE_TIME), TimeUnit.SECONDS);
if (isGetLock) {
orderInfo.setState(0);
if ("SUCCESS".equals(result)){ //接口成功
if (orderInfo.getStatus().equals(3))
orderInfo.setStatus(2);
else
orderInfo.setStatus(4);
} else { //接口失败
Integer refundCount = orderInfo.getRefundCount();
orderInfo.setRefundCount(refundCount + 1);
}
orderInfo.setApplicationStatus("1");
//redis key: 【order:activity:${aid}:${oid}】 value 【hash】;ttl:-1;hash state-> 【未同步】,status -> 退款中 (2 3)
cyRedisServiceImpl.set(RedisCons.ORDER_ACTIVITY +":"+ orderInfo.getGoodsId() + ":" + orderInfo.getBusinessId(),orderInfo);
//发送 mq,exchange:`order_activity` route-key:`order_activity_status` value 【订单】
// rabbitClusterUtil.sendMsg(orderInfo, rabbitMQConfigBean.ORDER_EXCHANGE_NAME, rabbitMQConfigBean.ORDER_STATUS_QUEUE_NAME);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
isGetLock = false;
} finally {
redisLock.unlock();
log.error("释放成功");
}
}
}
//任务:退款确认补救
@Transactional
public void executeRefundConfirmOrder() throws IOException, JDOMException {
// 查询DB进行中的活动订单,退款中(2),前50条
QueryWrapper<CmsOrder> wrapper = new QueryWrapper<>();
wrapper.in("status",2,4);
wrapper.eq("type",1);
wrapper.eq("del_flag",0);
wrapper.orderByAsc("refund_time");
wrapper.last("limit 50");
List<CmsOrder> orderInfoList = baseMapper.selectList(wrapper);
for (CmsOrder orderInfo : orderInfoList) {
// //主动查询订单退款状态接口
String result = wxPayService.selectWxOrderRefundStatus(orderInfo.getTransactionId());
//退款状态:
// SUCCESS—退款成功
// REFUNDCLOSE—退款关闭,指商户发起退款失败的情况。
// PROCESSING—退款处理中
// CHANGE—退款异常,退款到银行发现用户的卡作废或者冻结了,导致原路退款银行卡失败,可前往商户平台(pay.weixin.qq.com)-交易中心,手动处理此笔退款。
switch (result) {
case "SUCCESS" -> { //退款成功
log.info("SUCCESS--退款成功");
//加订单redis锁
boolean isGetLock = false;
RLock redisLock = redissonClient.getLock(RedisCons.ORDER_REDIS + orderInfo.getBusinessId());
try {
isGetLock = redisLock.tryLock(Long.parseLong(RedisCons.ORDER_INFO_LOCK_WAIT_TIME),
Long.parseLong(RedisCons.ORDER_INFO_LOCK_LEASE_TIME), TimeUnit.SECONDS);
if (isGetLock) {
Object detail = cyRedisServiceImpl.get(RedisCons.ORDER_ACTIVITY + ":" + orderInfo.getGoodsId() + ":" + orderInfo.getBusinessId());
if (detail != null) {
CmsOrder orderDetail = JSON.parseObject(JSON.toJSONString(detail), CmsOrder.class);
orderDetail.setState(0);
if (orderInfo.getStatus().equals(2))
orderDetail.setStatus(6);
else
orderDetail.setStatus(7);
orderDetail.setApplicationStatus("1");
//redis key: 【order:activity:${aid}:${oid}】 value 【hash】;ttl:-1;hash state-> 【未同步】,status -> 退款完成
cyRedisServiceImpl.set(RedisCons.ORDER_ACTIVITY + ":" + orderDetail.getGoodsId() + ":" + orderDetail.getBusinessId(), orderDetail);
//发送 mq,exchange:`order_activity` route-key:`order_activity_status` value 【订单】
// rabbitClusterUtil.sendMsg(orderDetail, rabbitMQConfigBean.ORDER_EXCHANGE_NAME, rabbitMQConfigBean.ORDER_STATUS_QUEUE_NAME);
}
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
isGetLock = false;
} finally {
redisLock.unlock();
log.error("释放成功");
}
}
case "REFUNDCLOSE" -> //退款关闭,指商户发起退款失败的情况。
log.info("REFUNDCLOSE--退款关闭,指商户发起退款失败的情况。");
case "PROCESSING" -> //退款处理中
log.info("PROCESSING—退款处理中");
case "CHANGE" -> //退款异常
log.info("CHANGE—退款异常");
default ->
log.info("订单退款状态查询失败");
}
}
}
//任务:订单缓存清除
@Transactional
public void executeDeleteOrder() {
// 查询DB,结束时间,近4个月的活动,如今日是2023-5-5,查询 2023-1-5 至2023-4-5 的活动
Date now = new Date();
Date startTime = TimeUtil.getTime(now, Calendar.MONTH,-4);
Date endTime = TimeUtil.getTime(now, Calendar.MONTH,-1);
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
QueryWrapper<CmsActivity> wrapper = new QueryWrapper<>();
wrapper.eq("del_flag",0);
wrapper.between("end_time",df.format(startTime),df.format(endTime));
List<CmsActivity> activityInfos = activityRepository.selectList(wrapper);
for (CmsActivity activity : activityInfos) {
//[order:activity:${aid}:*] 匹配
Set<String> map = redisTemplate.keys(RedisCons.ORDER_ACTIVITY+":"+activity.getBusinessId()+"*");
if (CollectionUtils.isNotEmpty(map)) {
for (String key : map) {
Object detail = cyRedisServiceImpl.get(key);
CmsOrder orderDetail = JSON.parseObject(JSON.toJSONString(detail), CmsOrder.class);
//state->已同步 => del key
if (Objects.equals(orderDetail.getState(),1))
redisTemplate.delete(key);
}
}
}
}
}
package org.rcisoft.core.schedule;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.rcisoft.business.cmsActivity.dao.CmsActivityRepository;
import org.rcisoft.business.cmsActivity.entity.CmsActivity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.util.Date;
import java.util.List;
@Component
@Slf4j
public class ActivitySyncSchedule {
@Autowired
private CmsActivityRepository activityInfoRepository;
//定时同步活动状态结束
// @Scheduled(cron = "0 0/10 * * * ?")
@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT)
public void execute() {
// 查询DB中的未删除的活动
QueryWrapper<CmsActivity> wrapper = new QueryWrapper<>();
wrapper.eq("del_flag",0);
List<CmsActivity> list = activityInfoRepository.selectList(wrapper);
for (CmsActivity activityInfo : list) {
//如果活动结束时间已过,改状态为已过期
if (activityInfo.getEndTime().before(new Date())) {
CmsActivity info = new CmsActivity();
info.setBusinessId(activityInfo.getBusinessId());
// info.setStatus(2);
// activityInfoRepository.updateById(info);
}
}
}
}
package org.rcisoft.core.schedule;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import lombok.extern.slf4j.Slf4j;
import org.jdom.JDOMException;
import org.rcisoft.app.pay.service.WxPayService;
import org.rcisoft.business.cmsActivity.dao.CmsActivityRepository;
import org.rcisoft.business.cmsActivity.entity.CmsActivity;
import org.rcisoft.business.cmsActivity.service.impl.StockService;
import org.rcisoft.business.cmsApplication.dao.CmsApplicationRepository;
import org.rcisoft.business.cmsApplication.entity.CmsApplication;
import org.rcisoft.business.cmsOrder.dao.CmsOrderRepository;
import org.rcisoft.business.cmsOrder.entity.CmsOrder;
import org.rcisoft.core.exception.CyServiceException;
import org.rcisoft.core.rabbitmq.bean.RabbitMQConfigBean;
import org.rcisoft.core.service.CyRedisService;
import org.rcisoft.core.util.RabbitClusterUtil;
import org.rcisoft.core.util.RedisCons;
import org.rcisoft.core.util.TimeUtil;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.io.IOException;
import java.math.BigDecimal;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;
@Component
@Slf4j
public class OrderSyncSchedule {
@Autowired(required = false)
private CyRedisService cyRedisServiceImpl;
@Autowired
private StringRedisTemplate redisTemplate;
// @Autowired
// private CouponInfoRepository couponInfoRepository;
@Autowired
private RedissonClient redissonClient;
@Autowired
private CmsOrderRepository orderInfoRepository;
@Autowired
private CmsApplicationRepository applicationRepository;
@Autowired
private CmsActivityRepository activityInfoRepository;
@Autowired
private WxPayService wxPayService;
@Autowired
private RabbitClusterUtil rabbitClusterUtil;
@Autowired
private StockService stockService;
@Autowired
private RabbitMQConfigBean rabbitMQConfigBean;
// @Autowired
// private IntegralAmountRelativeRepository integralAmountRelativeRepository;
//
// @Autowired
// private SysUserRepositorys sysUserRepositorys;
//
// @Autowired
// private UserIntegralRepository userIntegralRepository;
//
// @Autowired
// private MemberBenefitsRepository memberBenefitsRepository;
//任务:redis订单落库】5m 运行
@Scheduled(cron = "0 0/1 * * * ?")
@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT)
public void executeInsertOrder() throws NoSuchAlgorithmException {
// 查询 【order:activity:${所有}:${所有}】
Set<String> map = redisTemplate.keys(RedisCons.ORDER_ACTIVITY+"*");
if (CollectionUtils.isNotEmpty(map)) {
List<String>list = new ArrayList<>(map);
if (list.size()>50){
//过滤【随机】50条,【未同步】
Random sc = SecureRandom.getInstanceStrong();
for (int i = 0; i < 50; i++) {
// 随机一个索引
String key = list.get(sc.nextInt(list.size()));
insertOrder(key);
}
} else {
for (String key : list) {
insertOrder(key);
}
}
}
}
private void insertOrder(String key) {
Object detail = cyRedisServiceImpl.get(key);
CmsOrder orderDetail = JSON.parseObject(JSON.toJSONString(detail), CmsOrder.class);
if (orderDetail.getState().equals(0)){
//加redis锁 循环 redisson key:【order:db:${oid}】
boolean isGetLock = false;
RLock lock = redissonClient.getLock(RedisCons.ORDER_DB + orderDetail.getBusinessId());
try {
isGetLock = lock.tryLock(Long.parseLong(RedisCons.ORDER_INFO_LOCK_WAIT_TIME),
Long.parseLong(RedisCons.ORDER_INFO_LOCK_LEASE_TIME), TimeUnit.SECONDS);
if (isGetLock) {
//查询DB -> 是否已落库
CmsOrder info = orderInfoRepository.selectById(orderDetail.getBusinessId());
//未落库->落库;redis key: 【order:activity:${aid}:${oid}】【未同步】 => 落库
if (info == null) {
orderInfoRepository.insert(orderDetail);
//添加报名信息
CmsApplication application = new CmsApplication();
application.setUserId(orderDetail.getUserId());
application.setActivityId(orderDetail.getGoodsId());
application.setName(orderDetail.getAccount());
// application.setPhone(orderDetail.get);
//0 待支付 1已取消 2退款中 3退款中 4后台退款中 5后台退款中 6退款完成 7后台退款完成 8支付中 9 支付完成 10订单关闭
// if (orderDetail.getStatus().equals(0)||orderDetail.getStatus().equals(2)||orderDetail.getStatus().equals(3)||orderDetail.getStatus().equals(4)||
// orderDetail.getStatus().equals(5)||orderDetail.getStatus().equals(8)||orderDetail.getStatus().equals(9))
// application.setStatus("1");
// else if (orderDetail.getStatus().equals(1)||orderDetail.getStatus().equals(10))
// application.setStatus("2");
// else if (orderDetail.getStatus().equals(6)||orderDetail.getStatus().equals(7))
// application.setStatus("3");
application.setStatus(orderDetail.getApplicationStatus());
application.setApplicationFee(orderDetail.getPayPrice());
application.setOrderId(orderDetail.getBusinessId());
applicationRepository.insert(application);
// //如果有优惠券,进行核销
// if (orderDetail.getCouponId() != null) {
// UserCouponRelative userCouponRelative = new UserCouponRelative();
// userCouponRelative.setBusinessId(orderDetail.getCouponId());
// userCouponRelative.setCancelId(orderDetail.getStoreId());
// userCouponRelative.setOrderId(orderDetail.getBusinessId());
// userCouponRelative.setStatus(1);
// userCouponRelative.setCancelTime(new Date());
// couponInfoRepository.useCouponById(userCouponRelative);
// }
//加订单redis锁
RLock redisLock = redissonClient.getLock(RedisCons.ORDER_REDIS + orderDetail.getBusinessId());
try {
isGetLock = redisLock.tryLock(Long.parseLong(RedisCons.ORDER_INFO_LOCK_WAIT_TIME),
Long.parseLong(RedisCons.ORDER_INFO_LOCK_LEASE_TIME), TimeUnit.SECONDS);
if (isGetLock) {
//redis key: 【order:activity:${aid}:${oid}】 value 【hash】;ttl:-1;hash state-> 【已同步】
orderDetail.setState(1);
cyRedisServiceImpl.set(RedisCons.ORDER_ACTIVITY +":"+ orderDetail.getGoodsId() + ":" + orderDetail.getBusinessId(),orderDetail);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
isGetLock = false;
} finally {
redisLock.unlock();
log.error("释放成功");
}
} else {
//0 待支付 1已取消 2退款中 3退款中 4后台退款中 5后台退款中 6退款完成 7后台退款完成 8支付中 9 支付完成 10订单关闭
switch (orderDetail.getStatus()) {
case 0 ->//待支付
orderUpdateSatus(orderDetail);
case 1 ->//1已取消
orderCancel(orderDetail);
case 2 ->//2退款中
orderUpdateSatus(orderDetail);
case 3 ->//3退款中
orderUpdateSatus(orderDetail);
case 4 ->//4后台退款中
orderUpdateSatus(orderDetail);
case 5 ->//5后台退款中
orderUpdateSatus(orderDetail);
case 6 ->//6退款完成
orderUpdateSatus(orderDetail);
case 7 ->//7后台退款完成
orderUpdateSatus(orderDetail);
case 8 ->//8支付中
orderUpdateSatus(orderDetail);
case 9 ->//支付完成
orderFinish(orderDetail);
case 11 ->//11已核销
orderUpdateSatus(orderDetail);
default -> {
}
}
}
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
isGetLock = false;
} finally {
lock.unlock();
log.error("释放成功");
}
}
}
//支付完成
private void orderFinish(CmsOrder orderDetail) {
boolean isGetLock = false;
orderDetail.setUpdateDate(new Date());
orderInfoRepository.updateById(orderDetail);
CmsApplication application = applicationRepository.selectByOrderId(orderDetail.getBusinessId());
application.setStatus(orderDetail.getApplicationStatus());
applicationRepository.updateById(application);
//积分计算
// BigDecimal price = orderDetail.getPayPrice();
// IntegralAmountRelative relative = integralAmountRelativeRepository.queryIntegralByPrice(price);
// if (relative != null) {
// //查询会员信息
// SysUser info = sysUserRepositorys.selectUserById(orderDetail.getUserId());
// UserIntegral userIntegral = new UserIntegral();
// userIntegral.setUserId(orderDetail.getUserId());
// userIntegral.setGoodsId(orderDetail.getGoodsId());
// userIntegral.setChange(relative.getIntegral());
// Integer integral = info.getIntegral() + relative.getIntegral();
// userIntegral.setIntegral(integral);
// userIntegral.setCreateBy(String.valueOf(orderDetail.getUserId()));
// userIntegral.setCreateTime(new Date());
// userIntegralRepository.insertUserIntegral(userIntegral);
// //会员等级计算
// MemberBenefits benefits = memberBenefitsRepository.selectMemberBenefitsByLevel(info.getLevel()+1);
// if (benefits != null && (integral >= benefits.getIntegral())) {
// info.setLevel(info.getLevel()+1);
// }
// info.setIntegral(integral);
// sysUserRepositorys.updateSysUser(info);
// cyRedisServiceImpl.set(RedisCons.MEMBER_INFO + ":" + orderDetail.getUserId(), info);
// }
//加订单redis锁
RLock redisLock = redissonClient.getLock(RedisCons.ORDER_REDIS + orderDetail.getBusinessId());
try {
isGetLock = redisLock.tryLock(Long.parseLong(RedisCons.ORDER_INFO_LOCK_WAIT_TIME),
Long.parseLong(RedisCons.ORDER_INFO_LOCK_LEASE_TIME), TimeUnit.SECONDS);
if (isGetLock) {
//redis key: 【order:activity:${aid}:${oid}】 value 【hash】;ttl:-1;hash state-> 【已同步】
orderDetail.setState(1);
cyRedisServiceImpl.set(RedisCons.ORDER_ACTIVITY +":"+ orderDetail.getGoodsId() + ":" + orderDetail.getBusinessId(),orderDetail);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
isGetLock = false;
} finally {
redisLock.unlock();
log.error("释放成功");
}
}
//订单状态改为支付中
private void orderUpdateSatus(CmsOrder orderDetail) {
boolean isGetLock = false;
orderDetail.setUpdateDate(new Date());
orderInfoRepository.updateById(orderDetail);
CmsApplication application = applicationRepository.selectByOrderId(orderDetail.getBusinessId());
application.setStatus(orderDetail.getApplicationStatus());
applicationRepository.updateById(application);
//加订单redis锁
RLock redisLock = redissonClient.getLock(RedisCons.ORDER_REDIS + orderDetail.getBusinessId());
try {
isGetLock = redisLock.tryLock(Long.parseLong(RedisCons.ORDER_INFO_LOCK_WAIT_TIME),
Long.parseLong(RedisCons.ORDER_INFO_LOCK_LEASE_TIME), TimeUnit.SECONDS);
if (isGetLock) {
//redis key: 【order:activity:${aid}:${oid}】 value 【hash】;ttl:-1;hash state-> 【已同步】
orderDetail.setState(1);
cyRedisServiceImpl.set(RedisCons.ORDER_ACTIVITY +":"+ orderDetail.getGoodsId() + ":" + orderDetail.getBusinessId(),orderDetail);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
isGetLock = false;
} finally {
redisLock.unlock();
log.error("释放成功");
}
}
//订单状态改为已取消
private void orderCancel(CmsOrder orderDetail) {
boolean isGetLock = false;
orderDetail.setUpdateDate(new Date());
orderInfoRepository.updateById(orderDetail);
CmsApplication application = applicationRepository.selectByOrderId(orderDetail.getBusinessId());
application.setStatus(orderDetail.getApplicationStatus());
applicationRepository.updateById(application);
//订单优惠券退还
// if (orderDetail.getCouponId() != null) {
// UserCouponRelative userCouponRelative = new UserCouponRelative();
// userCouponRelative.setBusinessId(orderDetail.getCouponId());
// userCouponRelative.setStatus(0);
// couponInfoRepository.cancelCouponById(userCouponRelative);
// }
//加订单redis锁
RLock redisLock = redissonClient.getLock(RedisCons.ORDER_REDIS + orderDetail.getBusinessId());
try {
isGetLock = redisLock.tryLock(Long.parseLong(RedisCons.ORDER_INFO_LOCK_WAIT_TIME),
Long.parseLong(RedisCons.ORDER_INFO_LOCK_LEASE_TIME), TimeUnit.SECONDS);
if (isGetLock) {
//redis key: 【order:activity:${aid}:${oid}】 value 【hash】;ttl:-1;hash state-> 【已同步】
orderDetail.setState(1);
cyRedisServiceImpl.set(RedisCons.ORDER_ACTIVITY +":"+ orderDetail.getGoodsId() + ":" + orderDetail.getBusinessId(),orderDetail);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
isGetLock = false;
} finally {
redisLock.unlock();
log.error("释放成功");
}
}
//任务:redis订单关闭】5m 运行
@Scheduled(cron = "0 0/1 * * * ?")
@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT)
public void executeCloseOrder() throws NoSuchAlgorithmException {
// 查询 【order:activity:${所有}:${所有}】
Set<String> map = redisTemplate.keys(RedisCons.ORDER_ACTIVITY+"*");
if (CollectionUtils.isNotEmpty(map)) {
List<String>list = new ArrayList<>(map);
if (list.size()>50){
//过滤【随机】50条,state -> 待支付,大于30min
Random sc = SecureRandom.getInstanceStrong();
for (int i = 0; i < 50; i++) {
// 随机一个索引
String key = list.get(sc.nextInt(list.size()));
closeOrder(key);
}
} else {
for (String key : list) {
closeOrder(key);
}
}
}
}
private void closeOrder(String key) {
Object detail = cyRedisServiceImpl.get(key);
CmsOrder orderDetail = JSON.parseObject(JSON.toJSONString(detail), CmsOrder.class);
//status -> 待支付,大于30min
Date orderTime = orderDetail.getCreateDate();
Date a = new Date();
if (orderDetail.getStatus().equals(0) && a.getTime()-orderTime.getTime() > 1800000){
//加redis锁
boolean isGetLock = false;
RLock lock = redissonClient.getLock(RedisCons.ORDER_DB + orderDetail.getBusinessId());
try {
isGetLock = lock.tryLock(Long.parseLong(RedisCons.ORDER_INFO_LOCK_WAIT_TIME),
Long.parseLong(RedisCons.ORDER_INFO_LOCK_LEASE_TIME), TimeUnit.SECONDS);
if (isGetLock) {
// redis key: 【order:activity:${oid}】 value 【hash】;hash state 是否是 【待支付
orderDetail.setStatus(10);
orderDetail.setUpdateDate(new Date());
//查询DB -> 是否已落库
CmsOrder info = orderInfoRepository.selectById(orderDetail.getBusinessId());
if (info != null) {
orderInfoRepository.updateById(orderDetail);
CmsApplication application = applicationRepository.selectByOrderId(orderDetail.getBusinessId());
application.setStatus("2");
applicationRepository.updateById(application);
} else {
orderInfoRepository.insert(orderDetail);
//添加报名信息
CmsApplication application = new CmsApplication();
application.setUserId(orderDetail.getUserId());
application.setActivityId(orderDetail.getGoodsId());
application.setName(orderDetail.getAccount());
// application.setPhone(orderDetail.get);
//0 待支付 1已取消 2退款中 3退款中 4后台退款中 5后台退款中 6退款完成 7后台退款完成 8支付中 9 支付完成 10订单关闭
// if (orderDetail.getStatus().equals(0)||orderDetail.getStatus().equals(2)||orderDetail.getStatus().equals(3)||orderDetail.getStatus().equals(4)||
// orderDetail.getStatus().equals(5)||orderDetail.getStatus().equals(8)||orderDetail.getStatus().equals(9))
// application.setStatus("1");
// else if (orderDetail.getStatus().equals(1)||orderDetail.getStatus().equals(10))
// application.setStatus("2");
// else if (orderDetail.getStatus().equals(6)||orderDetail.getStatus().equals(7))
// application.setStatus("3");
application.setStatus("2");
application.setApplicationFee(orderDetail.getPayPrice());
application.setOrderId(orderDetail.getBusinessId());
applicationRepository.insert(application);
}
//如果使用了优惠券,则改为未使用
// if (orderDetail.getCouponId() != null) {
// UserCouponRelative userCouponRelative = new UserCouponRelative();
// userCouponRelative.setBusinessId(orderDetail.getCouponId());
// userCouponRelative.setStatus(0);
// couponInfoRepository.cancelCouponById(userCouponRelative);
// }
//加订单redis锁
RLock redisLock = redissonClient.getLock(RedisCons.ORDER_REDIS + orderDetail.getBusinessId());
try {
isGetLock = redisLock.tryLock(Long.parseLong(RedisCons.ORDER_INFO_LOCK_WAIT_TIME),
Long.parseLong(RedisCons.ORDER_INFO_LOCK_LEASE_TIME), TimeUnit.SECONDS);
if (isGetLock) {
//redis key: 【order:activity:${aid}:${oid}】 value 【hash】;ttl:-1;hash state-> 【已同步】
orderDetail.setState(1);
cyRedisServiceImpl.set(RedisCons.ORDER_ACTIVITY +":"+ orderDetail.getGoodsId() + ":" + orderDetail.getBusinessId(),orderDetail);
//退人数
// ActivityInfo activityInfo = activityInfoRepository.selectActivityInfoById(orderDetail.getGoodsId());
// if (activityInfo.getIsRestrictions().equals(0))
stockService.addStock(RedisCons.ACTIVITY_COUNT +":"+ orderDetail.getGoodsId(), 1);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
isGetLock = false;
} finally {
redisLock.unlock();
log.error("释放成功");
}
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
isGetLock = false;
} finally {
lock.unlock();
log.error("释放成功");
}
}
}
//任务:支付确认补救】15m 运行
@Scheduled(cron = "0 0/15 * * * ?")
@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT)
public void executePayOrder() throws IOException, JDOMException {
// 查询DB进行中的活动订单,支付中,前50条
QueryWrapper<CmsOrder> wrapper = new QueryWrapper<>();
wrapper.eq("status",8);
wrapper.eq("type",1);
wrapper.eq("del_flag",0);
wrapper.orderByAsc("order_time");
wrapper.last("limit 50");
List<CmsOrder> orderInfoList = orderInfoRepository.selectList(wrapper);
for (CmsOrder orderInfo : orderInfoList) {
//主动查询订单状态
String status = wxPayService.selectWxOrderStatus(String.valueOf(orderInfo.getBusinessId()));
switch (status) {
case "SUCCESS" -> { //支付成功
log.info("SUCCESS--支付成功");
//加订单redis锁
boolean isGetLock = false;
RLock redisLock = redissonClient.getLock(RedisCons.ORDER_REDIS + orderInfo.getBusinessId());
try {
isGetLock = redisLock.tryLock(Long.parseLong(RedisCons.ORDER_INFO_LOCK_WAIT_TIME),
Long.parseLong(RedisCons.ORDER_INFO_LOCK_LEASE_TIME), TimeUnit.SECONDS);
if (isGetLock) {
Object detail = cyRedisServiceImpl.get(RedisCons.ORDER_ACTIVITY + ":" + orderInfo.getGoodsId() + ":" + orderInfo.getBusinessId());
if (detail != null) {
CmsOrder orderDetail = JSON.parseObject(JSON.toJSONString(detail), CmsOrder.class);
orderDetail.setState(0);
orderDetail.setStatus(9);
orderDetail.setApplicationStatus("1");
//redis key: 【order:activity:${aid}:${oid}】 value 【hash】;ttl:-1;hash state-> 【未同步】,status -> 支付完成
cyRedisServiceImpl.set(RedisCons.ORDER_ACTIVITY + ":" + orderDetail.getGoodsId() + ":" + orderDetail.getBusinessId(), orderDetail);
//发送 mq,exchange:`order_activity` route-key:`order_activity_status` value 【订单】
// rabbitClusterUtil.sendMsg(orderDetail, rabbitMQConfigBean.ORDER_EXCHANGE_NAME, rabbitMQConfigBean.ORDER_STATUS_QUEUE_NAME);
}
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
isGetLock = false;
} finally {
redisLock.unlock();
log.error("释放成功");
}
}
case "REFUND" -> //转入退款
log.info("REFUND--转入退款");
case "NOTPAY" -> //未支付
log.info("NOTPAY--未支付");
case "CLOSED" -> //已关闭
log.info("CLOSED--已关闭");
case "REVOKED" -> //已撤销(刷卡支付)
log.info("REVOKED--已撤销(刷卡支付)");
case "USERPAYING" -> //用户支付中
log.info("USERPAYING--用户支付中");
case "PAYERROR" -> {//支付失败(其他原因,如银行返回失败)
log.info("PAYERROR--支付失败(其他原因,如银行返回失败)");
//加订单redis锁
boolean isGetLock = false;
RLock redisLock = redissonClient.getLock(RedisCons.ORDER_REDIS + orderInfo.getBusinessId());
try {
isGetLock = redisLock.tryLock(Long.parseLong(RedisCons.ORDER_INFO_LOCK_WAIT_TIME),
Long.parseLong(RedisCons.ORDER_INFO_LOCK_LEASE_TIME), TimeUnit.SECONDS);
if (isGetLock) {
Object detail = cyRedisServiceImpl.get(RedisCons.ORDER_ACTIVITY +":"+ orderInfo.getGoodsId() +":"+ orderInfo.getBusinessId());
if (detail!=null) {
CmsOrder orderDetail = JSON.parseObject(JSON.toJSONString(detail), CmsOrder.class);
//redis key: 【order:activity:${aid}:${oid}】 value 【hash】;ttl:-1;hash state-> 【未同步】,status -> 待支付
orderDetail.setState(0);
orderDetail.setStatus(0);
orderDetail.setApplicationStatus("1");
cyRedisServiceImpl.set(RedisCons.ORDER_ACTIVITY +":"+ orderDetail.getGoodsId() + ":" + orderDetail.getBusinessId(),orderDetail);
//发送 mq,exchange:`order_activity` route-key:`order_activity_status` value 【订单】
// rabbitClusterUtil.sendMsg(orderDetail, rabbitMQConfigBean.ORDER_EXCHANGE_NAME,rabbitMQConfigBean.ORDER_STATUS_QUEUE_NAME);
} else
throw new CyServiceException("订单支付失败,请稍后再试");
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
isGetLock = false;
} finally {
redisLock.unlock();
log.error("释放成功");
}
}
case "ACCEPT" -> //已接收,等待扣款
log.info("ACCEPT--已接收,等待扣款");
default ->
log.info("订单状态查询失败");
}
}
}
//任务:退款接口调用补救】30m 运行
@Scheduled(cron = "0 0/30 * * * ?")
@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT)
public void executeRefundOrder() {
// 查询DB进行中的活动订单,退款中(3 5),退款接口调用失败1,2,前50条
QueryWrapper<CmsOrder> wrapper = new QueryWrapper<>();
wrapper.in("status",3,5);
wrapper.eq("type",1);
wrapper.eq("del_flag",0);
wrapper.in("refund_count",1,2);
wrapper.orderByAsc("refund_time");
wrapper.last("limit 50");
List<CmsOrder> orderInfoList = orderInfoRepository.selectList(wrapper);
for (CmsOrder orderInfo : orderInfoList) {
//调用退款接口
String result = wxPayService.refundOrder(orderInfo);
//redisson key:【order:redis:${oid}】
boolean isGetLock = false;
RLock redisLock = redissonClient.getLock(RedisCons.ORDER_REDIS + orderInfo.getBusinessId());
try {
isGetLock = redisLock.tryLock(Long.parseLong(RedisCons.ORDER_INFO_LOCK_WAIT_TIME),
Long.parseLong(RedisCons.ORDER_INFO_LOCK_LEASE_TIME), TimeUnit.SECONDS);
if (isGetLock) {
orderInfo.setState(0);
if ("SUCCESS".equals(result)){ //接口成功
if (orderInfo.getStatus().equals(3))
orderInfo.setStatus(2);
else
orderInfo.setStatus(4);
} else { //接口失败
Integer refundCount = orderInfo.getRefundCount();
orderInfo.setRefundCount(refundCount + 1);
}
orderInfo.setApplicationStatus("1");
//redis key: 【order:activity:${aid}:${oid}】 value 【hash】;ttl:-1;hash state-> 【未同步】,status -> 退款中 (2 3)
cyRedisServiceImpl.set(RedisCons.ORDER_ACTIVITY +":"+ orderInfo.getGoodsId() + ":" + orderInfo.getBusinessId(),orderInfo);
//发送 mq,exchange:`order_activity` route-key:`order_activity_status` value 【订单】
// rabbitClusterUtil.sendMsg(orderInfo, rabbitMQConfigBean.ORDER_EXCHANGE_NAME, rabbitMQConfigBean.ORDER_STATUS_QUEUE_NAME);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
isGetLock = false;
} finally {
redisLock.unlock();
log.error("释放成功");
}
}
}
//任务:退款确认补救】30m 运行
@Scheduled(cron = "0 0/30 * * * ?")
@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT)
public void executeRefundConfirmOrder() throws IOException, JDOMException {
// 查询DB进行中的活动订单,退款中(2),前50条
QueryWrapper<CmsOrder> wrapper = new QueryWrapper<>();
wrapper.in("status",2,4);
wrapper.eq("type",1);
wrapper.eq("del_flag",0);
wrapper.orderByAsc("refund_time");
wrapper.last("limit 50");
List<CmsOrder> orderInfoList = orderInfoRepository.selectList(wrapper);
for (CmsOrder orderInfo : orderInfoList) {
// //主动查询订单退款状态接口
String result = wxPayService.selectWxOrderRefundStatus(orderInfo.getTransactionId());
//退款状态:
// SUCCESS—退款成功
// REFUNDCLOSE—退款关闭,指商户发起退款失败的情况。
// PROCESSING—退款处理中
// CHANGE—退款异常,退款到银行发现用户的卡作废或者冻结了,导致原路退款银行卡失败,可前往商户平台(pay.weixin.qq.com)-交易中心,手动处理此笔退款。
switch (result) {
case "SUCCESS" -> { //退款成功
log.info("SUCCESS--退款成功");
//加订单redis锁
boolean isGetLock = false;
RLock redisLock = redissonClient.getLock(RedisCons.ORDER_REDIS + orderInfo.getBusinessId());
try {
isGetLock = redisLock.tryLock(Long.parseLong(RedisCons.ORDER_INFO_LOCK_WAIT_TIME),
Long.parseLong(RedisCons.ORDER_INFO_LOCK_LEASE_TIME), TimeUnit.SECONDS);
if (isGetLock) {
Object detail = cyRedisServiceImpl.get(RedisCons.ORDER_ACTIVITY + ":" + orderInfo.getGoodsId() + ":" + orderInfo.getBusinessId());
if (detail != null) {
CmsOrder orderDetail = JSON.parseObject(JSON.toJSONString(detail), CmsOrder.class);
orderDetail.setState(0);
if (orderInfo.getStatus().equals(2))
orderDetail.setStatus(6);
else
orderDetail.setStatus(7);
orderDetail.setApplicationStatus("1");
//redis key: 【order:activity:${aid}:${oid}】 value 【hash】;ttl:-1;hash state-> 【未同步】,status -> 退款完成
cyRedisServiceImpl.set(RedisCons.ORDER_ACTIVITY + ":" + orderDetail.getGoodsId() + ":" + orderDetail.getBusinessId(), orderDetail);
//发送 mq,exchange:`order_activity` route-key:`order_activity_status` value 【订单】
// rabbitClusterUtil.sendMsg(orderDetail, rabbitMQConfigBean.ORDER_EXCHANGE_NAME, rabbitMQConfigBean.ORDER_STATUS_QUEUE_NAME);
}
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
isGetLock = false;
} finally {
redisLock.unlock();
log.error("释放成功");
}
}
case "REFUNDCLOSE" -> //退款关闭,指商户发起退款失败的情况。
log.info("REFUNDCLOSE--退款关闭,指商户发起退款失败的情况。");
case "PROCESSING" -> //退款处理中
log.info("PROCESSING—退款处理中");
case "CHANGE" -> //退款异常
log.info("CHANGE—退款异常");
default ->
log.info("订单退款状态查询失败");
}
}
}
//任务:订单缓存清除】每天凌晨 运行一次
@Scheduled(cron = "0 0 1 * * ?")
@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT)
public void executeDeleteOrder() {
// 查询DB,结束时间,近4个月的活动,如今日是2023-5-5,查询 2023-1-5 至2023-4-5 的活动
Date now = new Date();
Date startTime = TimeUtil.getTime(now, Calendar.MONTH,-4);
Date endTime = TimeUtil.getTime(now, Calendar.MONTH,-1);
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
QueryWrapper<CmsActivity> wrapper = new QueryWrapper<>();
wrapper.eq("del_flag",0);
wrapper.between("end_time",df.format(startTime),df.format(endTime));
List<CmsActivity> activityInfos = activityInfoRepository.selectList(wrapper);
for (CmsActivity activity : activityInfos) {
//[order:activity:${aid}:*] 匹配
Set<String> map = redisTemplate.keys(RedisCons.ORDER_ACTIVITY+":"+activity.getBusinessId()+"*");
if (CollectionUtils.isNotEmpty(map)) {
for (String key : map) {
Object detail = cyRedisServiceImpl.get(key);
CmsOrder orderDetail = JSON.parseObject(JSON.toJSONString(detail), CmsOrder.class);
//state->已同步 => del key
if (Objects.equals(orderDetail.getState(),1))
redisTemplate.delete(key);
}
}
}
}
}
package org.rcisoft.core.schedule;
import lombok.extern.slf4j.Slf4j;
import org.jdom.JDOMException;
import org.rcisoft.business.cmsOrder.service.impl.CmsOrderServiceImpl;
import org.rcisoft.business.memInfo.bean.MemberInfoRedisBean;
import org.rcisoft.business.memInfo.dao.MemInfoRepository;
import org.rcisoft.business.memInfo.entity.MemLikeDTO;
......@@ -13,6 +15,8 @@ import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.Map;
import java.util.Set;
......@@ -23,6 +27,8 @@ public class ScheduleTasks {
@Autowired
private MemInfoServiceImpl memInfoService;
@Autowired
private CmsOrderServiceImpl orderService;
/**
* 用户点赞数据定时任务 将点赞数据同步到对应的表中
......@@ -32,4 +38,58 @@ public class ScheduleTasks {
public void userLikeSchedule() {
memInfoService.userLikeSchedule();
}
/**
* redis订单落库
*/
@Scheduled(cron = "0 0/1 * * * ?")
public void executeInsertOrder() throws NoSuchAlgorithmException {
orderService.executeInsertOrder();
}
/**
* redis订单关闭
*/
@Scheduled(cron = "0 0/1 * * * ?")
public void executeCloseOrder() throws NoSuchAlgorithmException {
orderService.executeCloseOrder();
}
/**
* 支付确认补救
*/
@Scheduled(cron = "0 0/15 * * * ?")
public void executePayOrder() throws IOException, JDOMException {
orderService.executePayOrder();
}
/**
* 退款接口调用补救
*/
@Scheduled(cron = "0 0/30 * * * ?")
public void executeRefundOrder() {
orderService.executeRefundOrder();
}
/**
* 退款确认补救
*/
@Scheduled(cron = "0 0/30 * * * ?")
public void executeRefundConfirmOrder() throws IOException, JDOMException {
orderService.executeRefundConfirmOrder();
}
/**
* 订单缓存清除
*/
@Scheduled(cron = "0 0 1 * * ?")
public void executeDeleteOrder() {
orderService.executeDeleteOrder();
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment