您好,登錄后才能下訂單哦!
這期內容當中小編將會給大家帶來有關springboot+websocket怎樣實現并發搶紅包功能,文章內容豐富且以專業的角度為大家分析和敘述,閱讀完這篇文章希望大家可以有所收獲。
搶紅包功能作為幾大高并發場景中典型,應該如何實現?
參考微信搶紅包功能,將搶紅包分成一下幾個步驟:
發紅包;主要填寫紅包信息,生成紅包記錄
紅包支付回調;用戶發紅包支付成功后,收到微信支付付款成功的回調,生成指定數量的紅包。
搶紅包;用戶并發搶紅包。
拆紅包;記錄用戶搶紅包記錄,轉賬搶到的紅包金額。
項目使用sessionId模擬用戶,示例打開倆個瀏覽器窗口模擬兩個用戶。
紅包記錄在 redpacket
表中,用戶領取紅包詳情記錄在 redpacket_detail
表中。
CREATE DATABASE `redpacket`; use `redpacket`; CREATE TABLE `redpacket`.`redpacket` ( `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主鍵ID', `packet_no` varchar(32) NOT NULL COMMENT '訂單號', `amount` decimal(5,2) NOT NULL COMMENT '紅包金額最高10000.00元', `num` int(11) NOT NULL COMMENT '紅包數量', `order_status` int(4) NOT NULL DEFAULT '0' COMMENT '訂單狀態:0初始、1待支付、2支付成功、3取消', `pay_seq` varchar(32) DEFAULT NULL COMMENT '支付流水號', `create_time` datetime NOT NULL COMMENT '創建時間', `user_id` varchar(32) NOT NULL COMMENT '用戶ID', `update_time` datetime NOT NULL COMMENT '更新時間', `pay_time` datetime DEFAULT NULL COMMENT '支付時間', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='紅包訂單表'; CREATE TABLE `redpacket`.`redpacket_detail` ( `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主鍵ID', `packet_id` bigint(20) NOT NULL COMMENT '紅包ID', `amount` decimal(5,2) NOT NULL COMMENT '紅包金額', `received` int(1) NOT NULL DEFAULT '0' COMMENT '是否領取0未領取、1已領取', `create_time` datetime NOT NULL COMMENT '創建時間', `update_time` datetime NOT NULL COMMENT '更新時間', `user_id` varchar(32) DEFAULT NULL COMMENT '領取用戶', `packet_no` varchar(32) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='紅包詳情表';
用戶需要填寫紅包金額、紅包數量、備注信息等,生成紅包記錄,微信收銀臺下單,返回用戶支付。
public RedPacket generateRedPacket(ReqSendRedPacketsVO data,String userId) { final BigDecimal amount = data.getAmount(); //紅包數量 final Integer num = data.getNum(); //初始化訂單 final RedPacket redPacket = new RedPacket(); redPacket.setPacketNo(UUID.randomUUID().toString().replace("-", "")); redPacket.setAmount(amount); redPacket.setNum(num); redPacket.setUserId(userId); Date now = new Date(); redPacket.setCreateTime(now); redPacket.setUpdateTime(now); int i = redPacketMapper.insertSelective(redPacket); if (i != 1) { throw new ServiceException("生成紅包出錯", ExceptionType.SYS_ERR); } //模擬收銀臺下單 String paySeq = UUID.randomUUID().toString().replace("-", ""); //拿到收銀臺下單結果,更新訂單為待支付狀態 redPacket.setOrderStatus(1);//待支付 redPacket.setPaySeq(paySeq); i = redPacketMapper.updateByPrimaryKeySelective(redPacket); if (i != 1) { throw new ServiceException("生成紅包出錯", ExceptionType.SYS_ERR); } return redPacket; }
用戶支付成功后,系統接收到微信回調接口。
更新紅包支付狀態
二倍均值法生成指定數量紅包,并批量入庫。 紅包算法參考:Java實現4種微信搶紅包算法
紅包總數入redis,設置紅包過期時間24小時
websocket通知在線用戶收到新的紅包
@Transactional(rollbackFor = Exception.class) public void dealAfterOrderPayCallback(String userId,ReqOrderPayCallbackVO data) { RedPacketExample example = new RedPacketExample(); final String packetNo = data.getPacketNo(); final String paySeq = data.getPaySeq(); final Integer payStatus = data.getPayStatus(); example.createCriteria().andPacketNoEqualTo(packetNo) .andPaySeqEqualTo(paySeq) .andOrderStatusEqualTo(1);//待支付狀態 //更新訂單支付狀態 Date now = new Date(); RedPacket updateRedPacket = new RedPacket(); updateRedPacket.setOrderStatus(payStatus); updateRedPacket.setUpdateTime(now); updateRedPacket.setPayTime(now); int i = redPacketMapper.updateByExampleSelective(updateRedPacket, example); if (i != 1) { throw new ServiceException("訂單狀態更新失敗", ExceptionType.SYS_ERR); } if (payStatus == 2) { RedPacketExample query = new RedPacketExample(); query.createCriteria().andPacketNoEqualTo(packetNo) .andPaySeqEqualTo(paySeq) .andOrderStatusEqualTo(2); final RedPacket redPacket = redPacketMapper.selectByExample(query).get(0); final List<BigDecimal> detailList = getRedPacketDetail(redPacket.getAmount(), redPacket.getNum()); final int size = detailList.size(); if (size <= 100) { i = detailMapper.batchInsert(detailList, redPacket); if (size != i) { throw new ServiceException("生成紅包失敗", ExceptionType.SYS_ERR); } } else { int times = size % 100 == 0 ? size / 100 : (size / 100 + 1); for (int j = 0; j < times; j++) { int fromIndex = 100 * j; int toIndex = 100 * (j + 1) - 1; if (toIndex > size - 1) { toIndex = size - 1; } final List<BigDecimal> subList = detailList.subList(fromIndex, toIndex); i = detailMapper.batchInsert(subList, redPacket); if (subList.size() != i) { throw new ServiceException("生成紅包失敗", ExceptionType.SYS_ERR); } } } final String redisKey = REDPACKET_NUM_PREFIX + redPacket.getPacketNo(); String lua = "local i = redis.call('setnx',KEYS[1],ARGV[1])\r\n" + "if i == 1 then \r\n" + " local j = redis.call('expire',KEYS[1],ARGV[2])\r\n" + "end \r\n" + "return i"; //優化成lua腳本 final Long execute = redisTemplate.execute(new DefaultRedisScript<>(lua, Long.class), Arrays.asList(redisKey), size, 3600 * 24); if (execute != 1L) { throw new ServiceException("生成紅包失敗", ExceptionType.SYS_ERR); } //websocket通知在線用戶收到新的紅包 Websocket.sendMessageToUser(userId, JSONObject.toJSONString(redPacket)); } } /** * 紅包隨機算法 * * @param amount 紅包金額 * @param num 紅包數量 * @return 隨機紅包集合 */ private List<BigDecimal> getRedPacketDetail(BigDecimal amount, Integer num) { List<BigDecimal> redPacketsList = new ArrayList<>(num); //最小紅包金額 final BigDecimal min = new BigDecimal("0.01"); //最少需要紅包金額 final BigDecimal bigNum = new BigDecimal(num); final BigDecimal atLastAmount = min.multiply(bigNum); //出去最少紅包金額后剩余金額 BigDecimal remain = amount.subtract(atLastAmount); if (remain.compareTo(BigDecimal.ZERO) == 0) { for (int i = 0; i < num; i++) { redPacketsList.add(min); } return redPacketsList; } final Random random = new Random(); final BigDecimal hundred = new BigDecimal("100"); final BigDecimal two = new BigDecimal("2"); BigDecimal redPacket; for (int i = 0; i < num; i++) { if (i == num - 1) { redPacket = remain; } else { //100內隨機獲得的整數 final int rand = random.nextInt(100); redPacket = new BigDecimal(rand).multiply(remain.multiply(two).divide(bigNum.subtract(new BigDecimal(i)), 2, RoundingMode.CEILING)).divide(hundred, 2, RoundingMode.FLOOR); } if (remain.compareTo(redPacket) > 0) { remain = remain.subtract(redPacket); } else { remain = BigDecimal.ZERO; } redPacketsList.add(min.add(redPacket)); } return redPacketsList; }
頁面加載成功后初始化websocket,監聽后端新紅包生成成功,動態添加紅包到聊天窗口。
$(function (){ var websocket; if('WebSocket' in window) { console.log("此瀏覽器支持websocket"); websocket = new WebSocket("ws://127.0.0.1:8082/websocket/${session.id}"); } else if('MozWebSocket' in window) { alert("此瀏覽器只支持MozWebSocket"); } else { alert("此瀏覽器只支持SockJS"); } websocket.onopen = function(evnt) { console.log("鏈接服務器成功!") }; websocket.onmessage = function(evnt) { console.log(evnt.data); var json = eval('('+evnt.data+ ')'); obj.addPacket(json.id,json.packetNo,json.userId) }; websocket.onerror = function(evnt) {}; websocket.onclose = function(evnt) { console.log("與服務器斷開了鏈接!") } });
搶紅包設計高并發,本地單機項目,通過原子Integer控制搶紅包接口并發限制為20,
private AtomicInteger receiveCount = new AtomicInteger(0); @PostMapping("/receive") public CommonJsonResponse receiveOne(@Validated @RequestBody CommonJsonRequest<ReqReceiveRedPacketVO> vo) { Integer num = null; try { //控制并發不要超過20 if (receiveCount.get() > 20) { return new CommonJsonResponse("9999", "太快了"); } num = receiveCount.incrementAndGet(); final String s = orderService.receiveOne(vo.getData()); return StringUtils.isEmpty(s) ? CommonJsonResponse.ok() : new CommonJsonResponse("9999", s); } finally { if (num != null) { receiveCount.decrementAndGet(); } } }
對于沒有領取過該紅包的用戶,在紅包沒有過期且紅包還有剩余的情況下,搶紅包成功,記錄成功標識入redis,設置標識過期時間為5秒。
public String receiveOne(ReqReceiveRedPacketVO data) { final Long redPacketId = data.getPacketId(); final String redPacketNo = data.getPacketNo(); final String redisKey = REDPACKET_NUM_PREFIX + redPacketNo; if (!redisTemplate.hasKey(redisKey)) { return "紅包已經過期"; } final Integer num = (Integer) redisTemplate.opsForValue().get(redisKey); if (num <= 0) { return "紅包已搶完"; } RedPacketDetailExample example = new RedPacketDetailExample(); example.createCriteria().andPacketIdEqualTo(redPacketId) .andReceivedEqualTo(1) .andUserIdEqualTo(data.getUserId()); final List<RedPacketDetail> details = detailMapper.selectByExample(example); if (!details.isEmpty()) { return "該紅包已經領取過了"; } final String receiveKey = REDPACKET_RECEIVE_PREFIX + redPacketNo + ":" + data.getUserId(); //優化成lua腳本 String lua = "local i = redis.call('setnx',KEYS[1],ARGV[1])\r\n" + "if i == 1 then \r\n" + " local j = redis.call('expire',KEYS[1],ARGV[2])\r\n" + "end \r\n" + "return i"; //優化成lua腳本 final Long execute = redisTemplate.execute(new DefaultRedisScript<>(lua, Long.class), Arrays.asList(receiveKey), 1, 5); if (execute != 1L) { return "太快了"; } return ""; }
在用戶搶紅包成功標識未過期的狀態下,且紅包未過期紅包未領完時,從數據庫中領取一個紅包,領取成功將領取記錄寫入redis以供查詢過期時間為48小時。
@Transactional(rollbackFor = Exception.class) public String openRedPacket(ReqReceiveRedPacketVO data) { final Long packetId = data.getPacketId(); final String packetNo = data.getPacketNo(); final String userId = data.getUserId(); final String redisKey = REDPACKET_NUM_PREFIX + packetNo; Long num = null; try { final String receiveKey = REDPACKET_RECEIVE_PREFIX + packetNo + ":" + userId; if (!redisTemplate.hasKey(receiveKey)) { log.info("未獲取到紅包資格,packet:{},user:{}", packetNo, userId); throw new ServiceException("紅包飛走了", ExceptionType.SYS_ERR); } redisTemplate.delete(receiveKey); if (!redisTemplate.hasKey(redisKey)) { log.info("紅包過期了,packet:{}", packetNo); throw new ServiceException("紅包飛走了", ExceptionType.SYS_ERR); } num = redisTemplate.opsForValue().increment(redisKey, -1); if (num < 0L) { log.info("紅包領完了,packet:{}", packetNo); throw new ServiceException("紅包飛走了", ExceptionType.SYS_ERR); } final int i = detailMapper.receiveOne(packetId, packetNo, userId); if (i != 1) { log.info("紅包真的領完了,packet:{}", packetNo); throw new ServiceException("紅包飛走了", ExceptionType.SYS_ERR); } RedPacketDetailExample example = new RedPacketDetailExample(); example.createCriteria().andPacketIdEqualTo(packetId) .andReceivedEqualTo(1) .andUserIdEqualTo(userId); final List<RedPacketDetail> details = detailMapper.selectByExample(example); if (details.size() != 1) { log.info("已經領取過了,packet:{},user:{}", packetNo, userId); throw new ServiceException("紅包飛走了", ExceptionType.SYS_ERR); } //處理加款 log.info("搶到紅包金額{},packet:{},user:{}", details.get(0).getAmount(), packetNo, userId); final String listKey = REDPACKET_LIST_PREFIX + packetNo; redisTemplate.opsForList().leftPush(listKey,details.get(0)); redisTemplate.expire(redisKey, 48, TimeUnit.HOURS); return "" + details.get(0).getAmount(); } catch (Exception e) { if (num != null) { redisTemplate.opsForValue().increment(redisKey, 1L); } log.warn("打開紅包異常", e); throw new ServiceException("紅包飛走了", ExceptionType.SYS_ERR); } }
其中 detailMapper.receiveOne(packetId, packetNo, userId);
sql如下,將指定紅包記錄下未領取的紅包更新一條未當前用戶已經領取,若成功更新一條則表示領取成功,否則領取失敗。
update redpacket_detail d set received = 1,update_time = now(),user_id = #{userId,jdbcType=VARCHAR} where received = 0 and packet_id = #{packetId,jdbcType=BIGINT} and packet_no = #{packetNo,jdbcType=VARCHAR} and user_id is null limit 1
直接充redis中獲取用戶領取記錄,沒有則直接獲取數據庫并同步至redis。
public RespReceiveListVO receiveList(ReqReceiveListVO data) { //紅包記錄redisKey final String packetNo = data.getPacketNo(); final String redisKey = REDPACKET_LIST_PREFIX + packetNo; if (!redisTemplate.hasKey(redisKey)) { RedPacketDetailExample example = new RedPacketDetailExample(); example.createCriteria().andPacketNoEqualTo(packetNo) .andReceivedEqualTo(1); final List<RedPacketDetail> list = detailMapper.selectByExample(example); redisTemplate.opsForList().leftPushAll(redisKey, list); redisTemplate.expire(redisKey, 24, TimeUnit.HOURS); } List retList = redisTemplate.opsForList().range(redisKey, 0, -1); final Object collect = retList.stream().map(item -> { final JSONObject packetDetail = (JSONObject) item; return ReceiveRecordVO.builder() .amount(packetDetail.getBigDecimal("amount")) .receiveTime(packetDetail.getDate("updateTime")) .userId(packetDetail.getString("userId")) .packetId(packetDetail.getLong("redpacketId")) .packetNo(packetDetail.getString("redpacketNo")) .build(); }).collect(Collectors.toList()); return RespReceiveListVO.builder().list((List) collect).build(); }
設置jmeter參數1秒中并發請求50個搶11個紅包,可以看到,前面的請求都是成功的,中間并發量上來后有部分達到并發上限被攔截,后面紅包搶完請求全部失敗。
上述就是小編為大家分享的springboot+websocket怎樣實現并發搶紅包功能了,如果剛好有類似的疑惑,不妨參照上述分析進行理解。如果想知道更多相關知識,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。