How can I prevent concurrent lottery opportunities? The requirement is as follows: after a user posts data, I will give the user a lucky draw opportunity, that is, adding a record to the database. A user can only get one chance at most on the same day. How can we prevent multiple insert lottery opportunities due to concurrency during insert? How can we prevent concurrency?
The requirement is as follows: after a user posts data, I will give the user a lucky draw opportunity, that is, adding a record to the database. A user can only get one chance at most on the same day.
How to prevent multiple insert operations due to concurrency during insert?
Reply content:
How can I prevent concurrent lottery opportunities?
The requirement is as follows: after a user posts data, I will give the user a lucky draw opportunity, that is, adding a record to the database. A user can only get one chance at most on the same day.
How to prevent multiple insert operations due to concurrency during insert?
A good way isUser primary key+Activity id+That dayPerform the Union unique primary key constraint to insert a record.
Second, to prevent concurrency, add a lock. For example, you can use a pessimistic lock, that is
BeginSELECT * FROM table WHERE userid =? AND eventid =? AND current_day =? For update # judge whether it is null # Empty insert commit # Not empty error rollback
If the concurrency is high, select is not recommended.** For update operation, because the database may be dragged to death.
You can operate on the Optimistic Locking Mechanism
Update table set count = count-1, version = version + 1 where version = 123 and userid = 123
SetUser primary keyAndActivity idUnion unique primary key constraint
Solved, joined the primary key constraint, and used the mysqlINSERT IGNORE INTO tableCommand.
The insert operation of the database is locked.
One day can only have one chance. You can add a joint dimension-1 index to the userid and date fields, but you don't quite understand what it means to prevent concurrency ..
Queue or optimistic lock
Just make a unique index.