Home > Article > Backend Development > 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.
$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 { // 获取锁失败,处理业务逻辑 // ... }
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(); // 错误处理 // ... }
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) { // 操作失败,版本号不匹配,处理业务逻辑 // ... }
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(); // 错误处理 // ... }
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!