/
using-cas.php
66 lines (52 loc) · 1.8 KB
/
using-cas.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
66
<?php
use \Couchbase\ClusterOptions;
use \Couchbase\Cluster;
use \Couchbase\Collection;
use \Couchbase\ReplaceOptions;
use \Couchbase\CasMismatchError;
// #tag::increment[]
function incrementVisitCount(Collection $collection, string $userId) {
$maxRetries = 10;
for ($i = 0; $i < $maxRetries; $i++) {
// Get the current document contents
$res = $collection->get($userId);
// Increment the visit count
$user = $res->content();
$user["visit_count"]++;
try {
// Attempt to replace the document using CAS
$opts = new ReplaceOptions();
$opts->cas($res->cas());
$collection->replace($userId, $user, $opts);
} catch (CasMismatchError $ex) {
continue;
}
// If no errors occured during the replace, we can exit our retry loop
return;
}
printf("Replace failed after %d attempts\n", $maxRetries);
}
// #end::increment[]
function lockingAndCas(Collection $collection, string $userId) {
// #tag::locking[]
$res = $collection->getAndLock($userId, 2 /* seconds */);
$lockedCas = $res->cas();
/* // an example of simply unlocking the document:
* $collection->unlock($userId, $lockedCas);
*/
// Increment the visit count
$user = $res->content();
$user["visit_count"]++;
$opts = new ReplaceOptions();
$opts->cas($lockedCas);
$collection->replace($userId, $user, $opts);
// #end::locking[]
}
$opts = new ClusterOptions();
$opts->credentials("Administrator", "password");
$cluster = new Cluster("couchbase://192.168.1.101", $opts);
$bucket = $cluster->bucket("default");
$collection = $bucket->defaultCollection();
$collection->upsert("userId", ["visit_count" => 0]);
replaceWithCas($collection, "userId");
lockingAndCas($collection, "userId");