java微信延遲支付的實現(xiàn)示例
1.需求
下單支付后,支付回調因部分因素不可達,導致訂單狀態(tài)與微信支付狀態(tài)不一致。此時需要服務端主動查詢訂單支付狀態(tài),進行更改訂單狀態(tài)。
2.實現(xiàn)方式
基于定時任務
每隔30秒啟動一次,找出最近10分鐘內創(chuàng)建并且未支付的訂單,調用微信查單接口核實訂單狀態(tài)。系統(tǒng)記錄訂單查詢的次數(shù),在n次查詢之后狀態(tài)還是未支付成功,則停止后續(xù)查詢,并調用關單接口關閉訂單。
基于延時隊列
每隔5秒/30秒/1分鐘/3分鐘/5分鐘/10分鐘/30分鐘調用查單接口,若查詢付款成功,不再執(zhí)行隊列任務,最后一次查詢若還是未返回支付成功狀態(tài),則停止后續(xù)查詢,并調用《關單接口》關閉訂單。
延時隊列實現(xiàn)方式(這里不做詳細描述,優(yōu)缺點自行百度,本文采用redis實現(xiàn))
- delayqueue
- RabbitMQ
- reids
3.具體代碼
新建實體類 DelayQueueJob 與 ScoredSortedItem
/** * @Desecription: 延遲任務 * @Author: yangyu * @Date: 2021/9/10 14:35 */ @Data public class DelayQueueJob implements Serializable { /** * 延遲任務的唯一標識,用于檢索任務 */ private long jobId; /** * 任務的執(zhí)行時間段 */ private List<Long> delayTimeList; /** * 任務的執(zhí)行次數(shù) */ private Integer exCount = 0; /** * 任務的執(zhí)行時間單位 */ private TimeUnit timeUnit = TimeUnit.SECONDS; /** * 任務的執(zhí)行超時時間 */ private long timeout; /** * 訂單編號,根據(jù)編號查詢訂單 */ private String orderCode; /** * 任務類型(具體業(yè)務類型) */ private Integer topic; /** * 任務狀態(tài) 0:執(zhí)行 1:結束 */ private int jobType = 0; }
/** * @Desecription: 延時任務 桶 * @Author: yangyu * @Date: 2021/9/10 14:55 */ @Data @AllArgsConstructor public class ScoredSortedItem implements Serializable { /** * 延遲任務的唯一標識 */ private long jobId; /** * 任務的執(zhí)行時間 */ private long delayTime; }
定義常量
/** * @Desecription: 延時隊列常量 * @Author: yangyu * @Date: 2021/9/10 14:44 */ public class DelayQueueConstant { /* * 延時任務池 * */ public static final String DELAY_QUEUE_JOB_POOL = "delayQueue:delayQueueJobPool:"; /* * 延時桶 * */ public static final String DELAY_BUCKET_KEY_PREFIX = "delayQueue:delayBucket:"; /* * 任務的執(zhí)行時間段 * */ public static final List<Long> SLOT_DELAY_TIME = Arrays.asList(5L, 30L, 60L, 180L, 300L, 600L, 1800L); /* * 任務的執(zhí)行固定時間 * */ public static final List<Long> FIXED_DELAY_TIME = Arrays.asList(1800L); }
zset有序隊列操作類
/** * @Desecription: 以時間為維度的有序隊列zset 操作類,參考redisson_delay_queue_timeout * @Author: yangyu * @Date: 2021/9/10 14:50 */ @Component public class DelayBucket { @Autowired private RedissonClient redissonClient; /** * @Desecription: 添加jobId到延遲任務桶中 * @Param: key * @Param: jobId * @Param: delayTimeList * @Return: * @Author: yangyu * @Date: 2021/9/10 14:52 */ public void addToBucket(String key, Long jobId, List<Long> delayTimeList, TimeUnit timeUnit) { RScoredSortedSet<ScoredSortedItem> scoredSortedSet = redissonClient.getScoredSortedSet(DelayQueueConstant.DELAY_BUCKET_KEY_PREFIX + key); long millis = System.currentTimeMillis(); for (int i = 0; i < delayTimeList.size(); i++) { ScoredSortedItem scoredSortedItem = new ScoredSortedItem(jobId, millis + timeUnit.toMillis(delayTimeList.get(i))); scoredSortedSet.add(scoredSortedItem.getDelayTime(), scoredSortedItem); } } /** * @Desecription: 從延遲任務桶中獲取延遲時間最小的 jodId * @Param: jobIdKey * @Return: ScoredSortedItem * @Author: yangyu * @Date: 2021/9/10 15:35 */ public ScoredSortedItem getFromBucket(String key) { RScoredSortedSet<ScoredSortedItem> scoredSortedSet = redissonClient.getScoredSortedSet(DelayQueueConstant.DELAY_BUCKET_KEY_PREFIX + key); if (scoredSortedSet.size() == 0) { return null; } return scoredSortedSet.first(); } /** * @Desecription: 從延遲任務桶中刪除 jod * @Param: key * @Param scoredSortedItem * @Return: * @Author: yangyu * @Date: 2021/9/10 14:52 */ public void deleteFormBucket(String key, ScoredSortedItem scoredSortedItem) { RScoredSortedSet<ScoredSortedItem> scoredSortedSet = redissonClient.getScoredSortedSet(DelayQueueConstant.DELAY_BUCKET_KEY_PREFIX + key); scoredSortedSet.remove(scoredSortedItem); } }
延時任務類
/** * @Desecription: 操作延時任務 * @Author: yangyu * @Date: 2021/9/10 14:43 */ @Component public class DelayQueueJobPool { @Autowired private RedissonClient redissonClient; /** * @Desecription: 添加延時隊列job * @Param: delayQueueJob * @Author: yangyu * @Date: 2021/9/10 14:43 */ public void addDelayQueueJob(DelayQueueJob delayQueueJob, String key) { RMap<Long, DelayQueueJob> rMap = redissonClient.getMap(DelayQueueConstant.DELAY_QUEUE_JOB_POOL + key); rMap.put(delayQueueJob.getJobId(), delayQueueJob); } /** * @Desecription: 刪除延時隊列job * @Param: jobId * @Author: yangyu * @Date: 2021/9/10 14:46 */ public void deleteDelayQueueJob(Long jobId, String key) { RMap<Long, DelayQueueJob> rMap = redissonClient.getMap(DelayQueueConstant.DELAY_QUEUE_JOB_POOL + key); rMap.remove(jobId); } /** * @Desecription: 查詢延時隊列job * @Param: jobId * @Return: * @Author: yangyu * @Date: 2021/9/10 17:04 */ public DelayQueueJob getDelayQueueJob(Long jobId, String key) { RMap<Long, DelayQueueJob> rMap = redissonClient.getMap(DelayQueueConstant.DELAY_QUEUE_JOB_POOL + key); return rMap.get(jobId); } /** * @Desecription: 修改延時隊列job * @Param: jobId * @Author: yangyu * @Date: 2021/9/10 14:46 */ /** * @Desecription: 描述方法 * @Param: jobId * @Param: jobId * @Return: * @Author: yangyu * @Date: 2021/9/13 11:09 */ public void updateDelayQueueJob(DelayQueueJob delayQueueJob, String key) { RMap<Long, DelayQueueJob> rMap = redissonClient.getMap(DelayQueueConstant.DELAY_QUEUE_JOB_POOL + key); rMap.replace(delayQueueJob.getJobId(), delayQueueJob); } }
封裝api
@Log4j2 @Component public class RedisDelayedQueue { @Autowired private DelayQueueJobPool delayQueueJobPool; @Autowired private DelayBucket delayBucket; /** * @Desecription: 添加延遲任務到延遲隊列 * @Param: * @Author: yangyu * @Date: 2021/9/10 14:41 */ public void push(DelayQueueJob delayQueueJob, String simpleName) { delayQueueJobPool.addDelayQueueJob(delayQueueJob, simpleName); delayBucket.addToBucket(simpleName, delayQueueJob.getJobId(), delayQueueJob.getDelayTimeList(), delayQueueJob.getTimeUnit()); } }
隊列事件監(jiān)聽接口
/** * @Desecription: 隊列事件監(jiān)聽接口 * @Author: yangyu * @Date: 2021/9/10 10:11 */ public interface RedisDelayedQueueListenerService<T> { void invoke(T t); }
兩個接口實現(xiàn)類,主要分固定時間和延時時間,具體業(yè)務代碼就不貼出來了
/** * * @Desecription: 延時隊列監(jiān)聽 * @Author: yangyu * @Date: 2021/9/10 14:32 */ @Log4j2 @Service public class DelayedQueueSlotTime implements RedisDelayedQueueListenerService<DelayQueueJob> { @Autowired private WeChatPay chatPay; @Autowired private CrcxPayDetailService crcxPayDetailService; @Autowired private CrcxOrderService crcxOrderService; @Autowired private DelayQueueJobPool delayQueueJobPool; @Override public void invoke(DelayQueueJob delayQueueJob) { log.info("時間段執(zhí)行:{}", delayQueueJob); // topic == 1 查單延時任務 if (delayQueueJob.getTopic() == 1) { // 1.通過訂單編號,調用微信查單接口,查詢微信訂單支付狀態(tài)。 try { Map<String, String> queryOrder = chatPay.getQueryOrder(delayQueueJob.getOrderCode()); // 2.若已付款,對比系統(tǒng)訂單狀態(tài),未付款修改訂單狀態(tài),付款不做處理, String tradeState = queryOrder.get("tradeState"); if (tradeState.equalsIgnoreCase("SUCCESS")) { CrcxOrder crcxOrder = new CrcxOrder(); crcxOrder.setOrderCode(delayQueueJob.getOrderCode()); crcxOrder = crcxOrderService.getCrcxOrderByCode(crcxOrder); if (crcxOrder.getIsPay() == 0) { // 3.通過訂單編號 查 crcx_pay_detail 支付單-明細 CrcxPayDetail crcxPayDetail = new CrcxPayDetail(); crcxPayDetail.setTradeCode(delayQueueJob.getOrderCode()); crcxPayDetail = crcxPayDetailService.getPayDetail(crcxPayDetail); // 4.進行修改訂單狀態(tài) int update = crcxOrderService.updateOrderStatus(crcxPayDetail, queryOrder); if (update >= 1) { log.info("延時隊列:修改訂單支付狀態(tài)成功"); } else { log.error("延時隊列:修改訂單支付狀態(tài)失敗"); } } // 5.標記任務不需要再進業(yè)務邏輯。因為再 zset 中無法通過jobId 或者 訂單編號獲取對應的List delayQueueJob.setJobType(1); delayQueueJobPool.updateDelayQueueJob(delayQueueJob, this.getClass().getSimpleName()); } // 6.非已付款,不做任何處理,繼續(xù)執(zhí)行延時任務,直到執(zhí)行完畢,或者訂單已付款。 } catch (Exception e) { e.printStackTrace(); } } } } /** * * @Desecription: 固定時間隊列監(jiān)聽 * @Author: yangyu * @Date: 2021/9/10 13:18 */ @Log4j2 @Service public class DelayedQueueFixedTime implements RedisDelayedQueueListenerService<DelayQueueJob> { @Autowired private CrcxOrderService crcxOrderService; @Override public void invoke(DelayQueueJob delayQueueJob) { log.info("固定時間執(zhí)行...." + delayQueueJob.getJobId()); if (delayQueueJob != null) { // 查詢訂單狀態(tài)是否未支付狀態(tài) CrcxOrder crcxOrder = new CrcxOrder(); crcxOrder.setOrderCode(delayQueueJob.getOrderCode()); crcxOrder = crcxOrderService.getCrcxOrderByCode(crcxOrder); if (crcxOrder.getIsPay() == 0) { // 將待支付的訂單改為已取消(超時未支付) crcxOrder.setStatusCode(50); int ref = crcxOrderService.orderPaidTimeout(crcxOrder); if (ref == 0) throw new CustomException("自動取消訂單失敗"); } } } }
初始化隊列監(jiān)聽
/** * @Desecription: 初始化隊列監(jiān)聽 * @Author: yangyu * @Date: 2021/9/10 9:31 */ @Log4j2 @Component public class RedisDelayedQueueInit implements ApplicationContextAware { @Autowired private DelayBucket delayBucket; @Autowired private DelayQueueJobPool delayQueueJobPool; @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { Map<String, RedisDelayedQueueListenerService> map = applicationContext.getBeansOfType(RedisDelayedQueueListenerService.class); for (Map.Entry<String, RedisDelayedQueueListenerService> taskEventListenerEntry : map.entrySet()) { String listenerName = taskEventListenerEntry.getValue().getClass().getSimpleName(); startThread(listenerName, taskEventListenerEntry.getValue()); } } /** * @Desecription: 啟動線程獲取隊列 * @Param: queueName * @Param: redisDelayedQueueListenerService 任務回調監(jiān)聽 * @Return: * @Author: yangyu * @Date: 2021/9/10 11:32 */ private <T> void startThread(String queueName, RedisDelayedQueueListenerService redisDelayedQueueListenerService) { Thread thread = new Thread(() -> { // 有時間誤差,一般在一秒左右 log.info("啟動監(jiān)聽隊列線程:{}", queueName); while (true) { try { ScoredSortedItem item = delayBucket.getFromBucket(queueName); // 沒有任務就堵塞 if (item == null) { Thread.sleep(1000); continue; } // 延遲時間沒到 if (item.getDelayTime() > System.currentTimeMillis()) { Thread.sleep(1000); continue; } DelayQueueJob delayQueueJob = delayQueueJobPool.getDelayQueueJob(item.getJobId(), queueName); // 延遲任務數(shù)據(jù)不存在 if (delayQueueJob == null) { log.info("延遲任務數(shù)據(jù)不存在·····"); delayBucket.deleteFormBucket(queueName, item); Thread.sleep(1000); continue; } // 如果后面任務不需要執(zhí)行,不走業(yè)務邏輯,刪除正常執(zhí)行 if (delayQueueJob.getJobType() == 0) { new Thread(() -> { DelayQueueJob job = new DelayQueueJob(); BeanUtils.copyProperties(delayQueueJob, job); redisDelayedQueueListenerService.invoke(job); }).start(); } Integer exCount = delayQueueJob.getExCount(); if (exCount == 1) { delayQueueJobPool.deleteDelayQueueJob(delayQueueJob.getJobId(), queueName); delayBucket.deleteFormBucket(queueName, item); continue; } delayQueueJob.setExCount(--exCount); delayQueueJobPool.updateDelayQueueJob(delayQueueJob, queueName); delayBucket.deleteFormBucket(queueName, item); } catch (Exception e) { log.error("監(jiān)聽隊列線程錯誤:", e); try { Thread.sleep(10000); } catch (InterruptedException ex) { } } } }); thread.setName(queueName); thread.start(); } }
主要使用到的依賴包
<dependency> <groupId>org.redisson</groupId> <artifactId>redisson-spring-boot-starter</artifactId> <version>3.10.5</version> </dependency>
至此整個redis延時隊列就實現(xiàn)完成。
到此這篇關于java微信延遲支付的實現(xiàn)示例的文章就介紹到這了,更多相關java微信延遲支付內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Java詳細分析Lambda表達式與Stream流的使用方法
Lambda表達式,基于Lambda所帶來的函數(shù)式編程,又引入了一個全新的Stream概念,用于解決集合類庫既有的弊端,Lambda 允許把函數(shù)作為一個方法的參數(shù)(函數(shù)作為參數(shù)傳遞進方法中)。使用 Lambda 表達式可以使代碼變的更加簡潔緊湊2022-04-04Java Comparable和Comparator對比詳解
這篇文章主要介紹了Java Comparable和Comparator對比詳解,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2019-11-11