How does the "resolved" insert prevent concurrency?

Source: Internet
Author: User
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.

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.