溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

java+mysql中怎么實現(xiàn)商品搶購功能

發(fā)布時間:2021-06-18 09:53:57 來源:億速云 閱讀:251 作者:小新 欄目:編程語言

這篇文章主要為大家展示了“java+mysql中怎么實現(xiàn)商品搶購功能”,內(nèi)容簡而易懂,條理清晰,希望能夠幫助大家解決疑惑,下面讓小編帶領(lǐng)大家一起研究并學(xué)習(xí)一下“java+mysql中怎么實現(xiàn)商品搶購功能”這篇文章吧。

我們希望有人購買時檢查商品數(shù)量是否足夠,如果庫存有剩余那么就讓用戶購買成功,之后變更庫存,假如用戶排隊挨個購買這樣當(dāng)然沒有問題。

可是實際情況下,可能是用戶多個用戶同時來購買,同時檢查庫存,這是可能庫存僅夠其中一人購買,但是由于庫存還沒減掉,就會出現(xiàn)幾個人都購買成功,然后庫存減為負(fù)數(shù)出現(xiàn)超賣的情況。這在大量用戶在同一時間點同時購買時極可能出現(xiàn)。
于是我們調(diào)整一下順序,有用戶購買時我們先減掉庫存,那你肯定要問,怎么減?庫存不夠一個人的時候也減?
我們假設(shè)每份商品有一個唯一的購買碼(開始搶購前預(yù)先生成),用戶搶到購買碼的數(shù)量即他買到的份數(shù),那么有用戶購買時我們第一步就是給幸運碼的狀態(tài)由有效更改為無效,并為其標(biāo)記上其購買者ID

"UPDATE `lottery_number` SET `status` = 失效狀態(tài),`user_id` = 購買者用戶Id,`current_time`= 時間戳  WHERE `goods_id` = 搶購的商品ID AND `status`=有效狀態(tài) LIMIT 購買份數(shù) ";

這樣其實mysql會給我們一個返回結(jié)果,叫做影響行數(shù),就是說這條語句更新影響了多少行的數(shù)據(jù),這個影響行數(shù)就是他實際購買到的商品份數(shù),如果影響行數(shù)為0,就說明一份也沒購買成功,也就意味著商品已經(jīng)搶購?fù)瓿闪恕?/p>

java實現(xiàn):

/**
 * 生成商品的購買碼<大量數(shù)據(jù)插入>
 *
 * @param goodsIssue
 * @author Nifury
 */
public void insertLotteryNumbers(GoodsIssue goodsIssue) {
 String prefix = "INSERT INTO `lottery_number` (`goods_id`, `periods`,`luck_number`, `create_time`, `status`, `issue_id` ) VALUES \n";
 Timestamp now = new Timestamp(System.currentTimeMillis());
 Connection con = null;
 try {
  con = jdbcTemplate.getDataSource().getConnection();
  con.setAutoCommit(false);
  PreparedStatement pst = con.prepareStatement("");
  Long total = goodsIssue.getTotalShare();// 總?cè)舜?
  for (int i = 0; i < total; i += 10000) {// 1萬條提交一次
   StringBuffer suffix = new StringBuffer();
   List<Integer> numbers = new ArrayList<Integer>();
   for (int j = 0; j < 10000 && i+j < total; j++) {
    numbers.add(10000001 + i + j);
   }
   Collections.shuffle(numbers);//打亂幸運碼
   for (int n = 0,length = numbers.size(); n < length; n++) {
    suffix.append("(" + goodsIssue.getGoodsId() + ","
      + goodsIssue.getPeriods() + ","
      + numbers.get(n) + ",'" + now.toString() + "',"
      + 1 + "," + goodsIssue.getIssueId() + ")\n,");
   }
   // 構(gòu)建完整sql
   String sql = prefix + suffix.substring(0, suffix.length() - 2);
   pst.addBatch(sql);
   pst.executeBatch();
   con.commit();
  }
  con.setAutoCommit(true);// 還原
  pst.close();
  con.close();
 } catch (Exception e) {
  e.printStackTrace();
  try {// 事務(wù)回滾
   con.rollback();
   con.setAutoCommit(true);
   con.close();
  } catch (SQLException e1) {
   e1.printStackTrace();
  }// 還原
 }
}

分配購買碼(我們的業(yè)務(wù)需要給購買用戶展示購買碼,所以有返回)

/**
 * 通過商品issue_id(每期每個商品有唯一issue_id)來隨機獲取購買碼(使用的購買碼會設(shè)為失效狀態(tài))
 * @param issueId
 * @param amount 需要獲取的購買碼的數(shù)量
 * @param userId
 * @return LotteryNumber對象列表
 * @author Nifury 2016-7-22
 */
public List<LotteryNumber> queryByNewIssueId2(Long issueId, Long amount,Long userId) {
 List<LotteryNumber> numberList = new ArrayList<LotteryNumber>();
 try {
  long currentTime=System.currentTimeMillis();
  String updateUserId = "UPDATE `lottery_number` SET `status` = 0,`user_id` = ?,`current_time`= ? WHERE `issue_id` = ? AND `status`=1 LIMIT ? ";
  int rownum=jdbcTemplate.update(updateUserId, userId, currentTime, issueId, amount );
  if(rownum>0){//還有剩余有效購買碼
   Object[] buyargs={issueId, userId ,currentTime};
   numberList = jdbcTemplate.query(QUERY + " WHERE `issue_id` = ? AND `status` = 0 AND `user_id` = ? AND `current_time`= ?",
     buyargs, LotteryNumberMapper);
  }
 } catch (DeadlockLoserDataAccessException e) {
  System.out.println("----分配購買碼出現(xiàn)死鎖,用戶分得0個購買碼-----");
 }
 return numberList;
}

以上是“java+mysql中怎么實現(xiàn)商品搶購功能”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對大家有所幫助,如果還想學(xué)習(xí)更多知識,歡迎關(guān)注億速云行業(yè)資訊頻道!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI