SoFunction
Updated on 2025-04-04

Example code for PHP to implement Redis distributed lock

In distributed systems, ensuring secure access to shared resources is a critical task. Concurrent write problems may lead to inconsistent data or repeated writes. To solve this problem, we can use Redis to implement distributed locks to ensure that only one request can write data at the same time.

1. Why distributed locks are needed

In a high concurrency environment, multiple requests may arrive at the same time and attempt to modify the same resource. Without proper control, this can lead to inconsistent data or repeated writes. Distributed locking is a common solution that ensures that only one request can perform a write operation at the same time by locking it in a critical code segment.

2. Introduction to Redis distributed locks

Redis provides a simple and powerful distributed locking mechanism, where the SETNX (Set if Not eXists) command is the key. The SETNX command sets the key's value when the key does not exist, and does not do anything if the key already exists.

3. Use Redis distributed locks in PHP

The following is an example of using Redis distributed locks in PHP, and reference is made to the implementation of distributed locks in the Hyperf framework.

<?php

class RedisLock
{
    private $redis;
    private $lockKey;

    public function __construct($lockKey)
    {
        $this->redis = new Redis();
        $this->redis->connect('127.0.0.1', 6379);
        $this->lockKey = $lockKey;
    }

    public function acquireLock()
    {
        // Set the timeout time of the lock to prevent deadlock        $expire = 10;
        // Generate a unique identifier        $identifier = uniqid();

        while (!$this->redis->set($this->lockKey, $identifier, ['NX', 'EX' => $expire])) {
            // If the setting fails, wait for a while and try again            usleep(1000);
        }

        return $identifier;
    }

    public function releaseLock($identifier)
    {
        // Release the lock, check whether the identifier matches, and ensure that only requests holding the lock can be released        if ($this->redis->eval("if ('get',KEYS[1]) == ARGV[1] then return ('del',KEYS[1]) else return 0 end", [$this->lockKey, $identifier], 1)) {
            return true;
        }

        return false;
    }
}

// Example usage$lock = new RedisLock('my_resource');

// Try to acquire the lock$identifier = $lock->acquireLock();

if ($identifier) {
    // Acquisition the lock successfully and perform the operation that needs to be synchronized
    // Release the lock    $lock->releaseLock($identifier);
} else {
    // Failed to acquire the lock, handle conflict or retry logic    echo "Failed to acquire lock\n";
}

4. Refer to the implementation in the Hyperf framework

The distributed lock implementation in the Hyperf framework is more complex and uses Lua scripts to ensure atomicity. You can find more implementations in Hyperf's source code to suit different scenarios and performance requirements.

5. Advanced Topics and Optimizations

Considering factors such as timeout, retry mechanism, performance optimization, etc. are advanced topics when implementing distributed locks. In addition, appropriate optimization can be performed according to specific needs, such as using the RedLock algorithm, combining monitoring and alarm systems, etc.

6. Conclusion

By using Redis distributed locks, we can effectively prevent concurrent write problems, ensuring that only one request can write data at the same time. In practical applications, it is necessary to comprehensively consider factors such as the lock timeout and retry mechanism to improve the stability and availability of distributed locks.

This is the article about the example code of PHP implementing Redis distributed locks. For more related content of PHP Redis distributed locks, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!