How can lottery opportunities be issued to prevent concurrency?
The requirement is this: the user posts a piece of data I will give the user a lottery opportunity, that is, the database to add a record, a user can only get one chance on the day.
How to prevent inserts because of concurrency causes multiple inserts
Reply content:
How can lottery opportunities be issued to prevent concurrency?
The requirement is this: the user posts a piece of data I will give the user a lottery opportunity, that is, the database to add a record, a user can only get one chance on the day.
How to prevent inserts because of concurrency causes multiple inserts
The good way should be 用户主键
+ 活动id
+ 当天时间
to do the union unique PRIMARY KEY constraint, so that is the real insert a record
Next prevent concurrency should be added lock, like this can be used pessimistic lock, that is
beginSELECT * FROM table WHERE userid = ? AND eventid = ? AND current_day = ? for update# 判断是否为空 #为空 insert commit #不为空 error rollback
Concurrency is high, it is not recommended to use the Select *for update operation, because the database can be dragged to death.
You can operate with the optimistic locking mechanism
Update table set count= count-1,version=version+1 where version =123 and userid=123
Combine 用户主键
and 活动id
make union unique PRIMARY KEY constraint
Resolved, the Federated primary KEY constraint, as well as the use of MySQL INSERT IGNORE INTO table
command is OK.
The database insert operation itself is locked.
There can only be one chance a day, the UserID and the Date field plus a federated dimension index will do, not quite understand what it means to prevent concurrency.
Queue or optimistic lock
Just make a unique index.