-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path01-basic.php
65 lines (51 loc) · 1.82 KB
/
01-basic.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
<?php
declare(strict_types=1);
namespace RTCKit\React\Redlock\Examples;
error_reporting(-1);
require(__DIR__ . '/../vendor/autoload.php');
use Clue\React\Redis\Factory as RedisFactory;
use React\EventLoop\Loop;
use React\Promise\PromiseInterface;
use RTCKit\React\Redlock\Custodian;
use RTCKit\React\Redlock\Lock;
use Throwable;
use function React\Promise\resolve;
$host = getenv('REDLOCK_EXAMPLE_HOST');
if (!$host) {
$host = '127.0.0.1';
}
/* Instantiate prerequisites */
$factory = new RedisFactory();
$client = $factory->createLazyClient($host);
/* Instantiate our lock custodian */
$custodian = new Custodian($client);
Loop::addTimer(0.001, function () use ($custodian): void {
$custodian->acquire('01-basic', 1)
->then(function (?Lock $lock) use ($custodian): PromiseInterface {
if (is_null($lock)) {
echo "Failed to acquire lock!" . PHP_EOL;
return resolve(false);
} else {
echo "Successfully acquired lock!" . PHP_EOL;
echo "> Resource: " . $lock->getResource() . PHP_EOL;
echo "> TTL: " . $lock->getTTL() . PHP_EOL;
echo "> Token: " . $lock->getToken() . PHP_EOL;
echo "About to release lock ..." . PHP_EOL;
return $custodian->release($lock);
}
})
->then(function (bool $success): void {
if ($success) {
echo "Successfully released lock!" . PHP_EOL;
} else {
echo "Failed to release lock!" . PHP_EOL;
}
})
->otherwise(function (Throwable $t): void {
echo "Something bad happened:" . PHP_EOL . " > " . $t->getMessage() . PHP_EOL;
})
->always(function(): void {
Loop::stop();
echo "Bye!" . PHP_EOL;
});
});