How to deal with distributed locks and concurrency control in PHP development

WBOY
Release: 2023-10-08 11:50:02
Original
1245 people have browsed it

How to deal with distributed locks and concurrency control in PHP development

Title: Distributed lock and concurrency control practice in PHP development

In high-concurrency web application development, distributed lock and concurrency control are essential technical means. This article will introduce how to use PHP to handle distributed locks and concurrency control, with specific code examples.

  1. The concept of distributed lock
    Distributed lock refers to a mechanism that ensures the order and consistency of data operations for a certain resource in a distributed system. In high-concurrency scenarios, distributed locks can prevent multiple processes from accessing and modifying the same resource at the same time, thereby ensuring data accuracy.
  2. Distributed lock implementation method
    2.1 Cache-based implementation
    Using cache to implement distributed locks is a common and simple way, and can be implemented using cache services such as Redis and Memcached.
    The sample code is as follows:
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);

$lockKey = 'resource_lock';
$lockExpire = 10;

// 尝试获取锁
$lockResult = $redis->set($lockKey, 1, ['NX', 'EX' => $lockExpire]);

if ($lockResult) {
    // 获取锁成功,执行业务逻辑
    // ...

    // 释放锁
    $redis->del($lockKey);
} else {
    // 获取锁失败,处理业务逻辑
    // ...
}
Copy after login

2.2 Database-based implementation
Simulate a distributed lock by adding a new table in the database, and use the transaction characteristics of the database to implement the lock function.
The sample code is as follows:

// 假设数据库连接已经创建
$lockTable = 'resource_lock';
$lockExpire = 10;

$pdo->beginTransaction();

try {
    // 尝试获取锁
    $selectSql = "SELECT * FROM $lockTable WHERE resource='resource_key' FOR UPDATE";
    $selectStmt = $pdo->prepare($selectSql);
    $selectStmt->execute();

    $lockRow = $selectStmt->fetch(PDO::FETCH_ASSOC);

    if ($lockRow) {
        // 锁已经存在,获取锁失败,处理业务逻辑
        // ...
    } else {
        // 锁不存在,获取锁成功,执行业务逻辑
        // ...

        // 插入锁信息
        $insertSql = "INSERT INTO $lockTable (resource, create_time) VALUES ('resource_key', UNIX_TIMESTAMP())";
        $insertStmt = $pdo->prepare($insertSql);
        $insertStmt->execute();

        // 提交事务
        $pdo->commit();
    }
} catch (Exception $e) {
    // 发生异常,回滚事务
    $pdo->rollback();

    // 错误处理
    // ...
}
Copy after login
  1. How to implement concurrency control
    Concurrency control refers to a control method to ensure data consistency in a high-concurrency environment. Common concurrency control methods include optimistic locking and pessimistic locking.

3.1 Optimistic lock implementation
Optimistic lock means that before performing data operations, it is presupposed that no conflict will occur, and only determines whether it matches the previous version number during the update, and executes it if it matches. Update operation, otherwise an error message is returned.
The sample code is as follows:

// 假设从数据库中获取到的数据是当前版本号为2的数据
$data = [
    'id' => 1,
    'name' => 'test',
    'version' => 2
];

$optimizedVersion = $data['version'] + 1;

// 更新数据
$updateSql = "UPDATE resource_table SET name='updated_name', version=$optimizedVersion WHERE id=1 AND version={$data['version']}";
$updateStmt = $pdo->prepare($updateSql);
$updateStmt->execute();

if ($updateStmt->rowCount() <= 0) {
    // 操作失败,版本号不匹配,处理业务逻辑
    // ...
}
Copy after login

3.2 Pessimistic lock implementation
Pessimistic lock means to obtain the lock before performing data operations to ensure that the current user can exclusively occupy the data and other users cannot modify the data until the current The user releases the lock.
The sample code is as follows:

$pdo->beginTransaction();

try {
    // 获取锁
    $selectSql = "SELECT * FROM resource_table WHERE id=1 FOR UPDATE";
    $selectStmt = $pdo->prepare($selectSql);
    $selectStmt->execute();

    $data = $selectStmt->fetch(PDO::FETCH_ASSOC);

    if ($data) {
        // 获取锁成功,执行业务逻辑
        // ...

        // 释放锁
        $pdo->commit();
    } else {
        // 获取锁失败,处理业务逻辑
        // ...
    }
} catch (Exception $e) {
    // 发生异常,回滚事务
    $pdo->rollback();

    // 错误处理
    // ...
}
Copy after login

Summary:
In PHP development, distributed locks and concurrency control are important means to achieve high concurrency and data consistency. This article introduces the implementation of distributed locks based on cache and database, as well as the implementation of concurrency control of optimistic locks and pessimistic locks, and comes with specific code examples. I hope it can help readers better handle distributed locks and concurrency in development. Controlled scene.

The above is the detailed content of How to deal with distributed locks and concurrency control in PHP development. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!