PHP code example of ihongwu / redis-redlock
1. Go to this page and download the library: Download ihongwu/redis-redlock library . Choose the download type require .
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
ihongwu / redis-redlock example snippets
use RedisLock\RedisRedLock;
// 有自动加载则不需要
password' => '88888888'],
['host' => '127.0.0.1', 'port' => 6392, 'password' => '88888888'],
['host' => '127.0.0.1', 'port' => 6393, 'password' => '88888888'],
];
$resourceKey = 'my_distributed_lock';
try {
$redlock = new RedisRedLock($servers, $resourceKey);
if ($redlock->lock()) {
echo "成功获取锁,执行任务...\n";
if ($redlock->lock()) {
echo "再次获取锁,继续执行任务...\n";
}
if ($redlock->unlock()) {
echo "锁已释放一次。\n";
}
if ($redlock->unlock()) {
echo "锁已全部释放。\n";
}
} else {
echo "获取锁失败。\n";
}
} catch (\Exception $e) {
var_dump($e->getMessage());
}
// 配置信息
return [
'6391' => [
'host' => '127.0.0.1',
'password' => '88888888',
'port' => 6391,
'database' => 0,
'pool' => [
'min' => 5,
'max' => 50,
'timeout' => 5
]
],
'6392' => [
'host' => '127.0.0.1',
'password' => '88888888',
'port' => 6392,
'database' => 0,
'pool' => [
'min' => 5,
'max' => 50,
'timeout' => 5
]
],
'6393' => [
'host' => '127.0.0.1',
'password' => '88888888',
'port' => 6393,
'database' => 0,
'pool' => [
'min' => 5,
'max' => 50,
'timeout' => 5
]
],
];
use RedisLock\RedisRedLock;
// 不想传入连接池的,也可以直接传入Redis配置信息
// 连接成功的redis实例,才给锁对象使用
$servers = [];
try {
$servers[] = Redis::connection('6391')->client();
} catch (\Exception $e) {}
try {
$servers[] = Redis::connection('6392')->client();
} catch(\Exception $e) {}
try {
$servers[] = Redis::connection('6393')->client();
} catch(\Exception $e) {}
$resourceKey = 'my_distributed_lock';
try {
$redlock = new RedisRedLock($servers, $resourceKey);
if ($redlock->lock()) {
echo "成功获取锁,执行任务...\n";
if ($redlock->lock()) {
echo "再次获取锁,继续执行任务...\n";
}
if ($redlock->unlock()) {
echo "锁已释放一次。\n";
}
if ($redlock->unlock()) {
echo "锁已全部释放。\n";
}
} else {
echo "获取锁失败。\n";
}
} catch (\Exception $e) {
var_dump($e->getMessage());
}