Concurrency problems encountered in record time work

Foreword

  First talk about business scenarios: video store all our systems on third party cloud platform, we need to call its interface to operate the video. Due to third-party platforms, this operation there may be a delay of 0-30 seconds, during which time if there are other requests to operate the video will appear concurrency issues (video only allowed to operate once).

solution

    The system is a distributed system, the conventional use of other synchronous operation synchronous queue can not be used, so the use of a distributed lock to solve this problem. Distributed lock implementations are generally three ways: 1 based on the lock on the database; 2 Redis based lock; 3 ZK-based lock....

  About Distributed Lock I will write a follow-up blog post here because the business logic does not require very high reliability because of its own concurrency is not high, so the use of the most simple lock-based database.

  Database lock is the use of a unique index database when a request is received, it will insert a data into the database, if successful insertion of said lock acquisition success, or failure. Flowchart is as follows:

  The core lock step as follows:

     1. After first use will receive a user request data to the database insert, to acquire the lock to succeed if it means the video is the first operation to start operation.

    2. If the failure is determined whether a lock acquisition operation timed out, if the video out will be done once again, no timeout is not any treatment.

  PS: the introduction of overtime because here is because if the video is being operated, this time the collapse of the server, so that when a user requests a second operation this video can restart operations.

  In fact, the above two judgments can be completed using a SQL:

INSERT INTO lock_table(video_id, STATUS, overtime)
VALUES
    (#{videoId},#{status},#{overtime})
WHERE
    NOT EXISTS (
        SELECT
            1
        FROM
            lock_table
        WHERE
            video_id = #{videoId}
        AND CURRENT_TIMESTAMP () > overtime
    )

  当第一次操作该视频时where条件返回true可以正常获取锁,当第二次操作该视频且操作未超时,则where条件返回false,当第二次操作该视频且操作超时,where条件返回true但是SQL会报错,以此来表示操作超时。

Guess you like

Origin www.cnblogs.com/ouhaitao/p/11078297.html
Recommended