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
|
// Developers can customize the distribution strategy used by the client
|
15
|
// to distribute keys among a cluster of servers simply by creating a class
|
16
|
// that implements Predis\Distribution\DistributionStrategyInterface.
|
17
|
|
18
|
use Predis\Connection\PredisCluster;
|
19
|
use Predis\Cluster\Distribution\DistributionStrategyInterface;
|
20
|
use Predis\Cluster\Hash\HashGeneratorInterface;
|
21
|
|
22
|
class NaiveDistributionStrategy implements DistributionStrategyInterface, HashGeneratorInterface
|
23
|
{
|
24
|
private $nodes;
|
25
|
private $nodesCount;
|
26
|
|
27
|
public function __construct()
|
28
|
{
|
29
|
$this->nodes = array();
|
30
|
$this->nodesCount = 0;
|
31
|
}
|
32
|
|
33
|
public function add($node, $weight = null)
|
34
|
{
|
35
|
$this->nodes[] = $node;
|
36
|
$this->nodesCount++;
|
37
|
}
|
38
|
|
39
|
public function remove($node)
|
40
|
{
|
41
|
$this->nodes = array_filter($this->nodes, function ($n) use ($node) {
|
42
|
return $n !== $node;
|
43
|
});
|
44
|
|
45
|
$this->nodesCount = count($this->nodes);
|
46
|
}
|
47
|
|
48
|
public function get($key)
|
49
|
{
|
50
|
if (0 === $count = $this->nodesCount) {
|
51
|
throw new RuntimeException('No connections');
|
52
|
}
|
53
|
|
54
|
return $this->nodes[$count > 1 ? abs($key % $count) : 0];
|
55
|
}
|
56
|
|
57
|
public function hash($value)
|
58
|
{
|
59
|
return crc32($value);
|
60
|
}
|
61
|
|
62
|
public function getHashGenerator()
|
63
|
{
|
64
|
return $this;
|
65
|
}
|
66
|
}
|
67
|
|
68
|
$options = array(
|
69
|
'cluster' => function () {
|
70
|
$distributor = new NaiveDistributionStrategy();
|
71
|
$cluster = new PredisCluster($distributor);
|
72
|
|
73
|
return $cluster;
|
74
|
},
|
75
|
);
|
76
|
|
77
|
$client = new Predis\Client($multiple_servers, $options);
|
78
|
|
79
|
for ($i = 0; $i < 100; $i++) {
|
80
|
$client->set("key:$i", str_pad($i, 4, '0', 0));
|
81
|
$client->get("key:$i");
|
82
|
}
|
83
|
|
84
|
$server1 = $client->getClientFor('first')->info();
|
85
|
$server2 = $client->getClientFor('second')->info();
|
86
|
|
87
|
printf("Server '%s' has %d keys while server '%s' has %d keys.\n",
|
88
|
'first', $server1['db15']['keys'], 'second', $server2['db15']['keys']
|
89
|
);
|