1
|
<?php
|
2
|
|
3
|
/*
|
4
|
* This file is part of the Predis package.
|
5
|
*
|
6
|
* (c) Daniele Alessandri <suppakilla@gmail.com>
|
7
|
*
|
8
|
* For the full copyright and license information, please view the LICENSE
|
9
|
* file that was distributed with this source code.
|
10
|
*/
|
11
|
|
12
|
require 'SharedConfigurations.php';
|
13
|
|
14
|
// This is an implementation of an atomic client-side ZPOP using the support for
|
15
|
// check-and-set (CAS) operations with MULTI/EXEC transactions, as described in
|
16
|
// "WATCH explained" from http://redis.io/topics/transactions
|
17
|
//
|
18
|
// First, populate your database with a tiny sample data set:
|
19
|
//
|
20
|
// ./redis-cli
|
21
|
// SELECT 15
|
22
|
// ZADD zset 1 a
|
23
|
// ZADD zset 2 b
|
24
|
// ZADD zset 3 c
|
25
|
|
26
|
function zpop($client, $key)
|
27
|
{
|
28
|
$element = null;
|
29
|
$options = array(
|
30
|
'cas' => true, // Initialize with support for CAS operations
|
31
|
'watch' => $key, // Key that needs to be WATCHed to detect changes
|
32
|
'retry' => 3, // Number of retries on aborted transactions, after
|
33
|
// which the client bails out with an exception.
|
34
|
);
|
35
|
|
36
|
$client->transaction($options, function ($tx) use ($key, &$element) {
|
37
|
@list($element) = $tx->zrange($key, 0, 0);
|
38
|
|
39
|
if (isset($element)) {
|
40
|
$tx->multi(); // With CAS, MULTI *must* be explicitly invoked.
|
41
|
$tx->zrem($key, $element);
|
42
|
}
|
43
|
});
|
44
|
|
45
|
return $element;
|
46
|
}
|
47
|
|
48
|
$client = new Predis\Client($single_server);
|
49
|
$zpopped = zpop($client, 'zset');
|
50
|
|
51
|
echo isset($zpopped) ? "ZPOPed $zpopped" : "Nothing to ZPOP!", "\n";
|