Java + mysql to achieve the product flash sales function, javamysql product flash sales
We want someone to check whether the quantity of items is sufficient when buying the product. If there is surplus inventory, let the user buy the product successfully, and then change the inventory. If the user queues to buy one by one, of course, this is no problem.
However, in actual situations, multiple users may purchase the product at the same time and check the inventory. This may be because the inventory is only enough for one of them to purchase, but the inventory has not been reduced, the purchase is successful for several people, and then the inventory is reduced to a negative number. This is very likely to happen when a large number of users buy at the same time.
So Let's adjust the order. When a user buys the product, we first lose the inventory. Then you must ask, How can we reduce it? When there is not enough inventory for one person?
Assume that each item has a unique purchase code (pre-generated before the flash sale starts). The number of purchased codes that a user grabs is the number of copies he buys, when a user purchases an accesskey, the first step is to change the status of the lucky code from valid to invalid and mark it with its purchaser ID.
Copy codeThe Code is as follows: "UPDATE 'lottery _ number' SET 'status' = invalid, 'user _ id' = purchaser user id, 'Current _ time' = timestamp WHERE 'goods _ id' = the id of the purchased item AND 'status' = valid LIMIT number of purchased parts ";
In this case, mysql will give us a returned result, called the number of affected rows, that is, the number of rows affected by this statement update is the number of items actually purchased by the statement, if the number of affected rows is 0, it means that one copy is not successfully purchased, which means that the product has been snapped up.
Java implementation:
/*** Generate the purchase code of the product <insert large volume of data> ** @ 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 (); // total times for (int I = 0; I <total; I ++ = 10000) {// submit StringBuffer suffix = new StringBuffer () once (); list <Integer> numbers = new ArrayList <Integer> (); for (int j = 0; j <10000 & I + j <total; j ++) {numbers. add (10000001 + I + j);} Collections. shuffle (numbers); // disrupt the lucky code 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,");} // construct the complete SQL String SQL = prefix + suffix. substring (0, suffix. length ()-2); pst. addBatch (SQL); pst.exe cuteBatch (); con. commit ();} con. setAutoCommit (true); // restore pst. close (); con. close ();} catch (Exception e) {e. printStackTrace (); try {// transaction rollback con. rollback (); con. setAutoCommit (true); con. close () ;}catch (SQLException e1) {e1.printStackTrace () ;}// restore }}
Allocate the purchase code (our business needs to show the purchase code to the purchase user, so there is a return)
/*** Get the purchase code randomly through the issue_id (each item has a unique issue_id) (the purchase code used is set to invalid) * @ param issueId * @ param amount Number of purchase codes to be obtained * @ param userId * @ return LotteryNumber object List * @ 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) {// There are still valid purchase codes for 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 ("---- the allocation purchase code has a deadlock. The user gets 0 purchase codes -----");} return numberList ;}
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.