Skip to content

Instantly share code, notes, and snippets.

@netmarkjp
Last active August 29, 2015 14:13
Show Gist options
  • Save netmarkjp/5c0277f83b665d32416b to your computer and use it in GitHub Desktop.
Save netmarkjp/5c0277f83b665d32416b to your computer and use it in GitHub Desktop.
PHP consistent hashing with Memcache module (not Memcached module)
[root@lc6 ~]# for i in `seq 1 4`; do memcached -d -p 1121${i} -u memcached -m 64 -c 1024 -P /var/run/memcached/memcached${i}.pid ;done
[root@lc6 ~]# php set.php
[root@lc6 ~]# php get.php
key1:1 key2:2 key3:3 key4:4 key5:5 key6:6 key7:7 key8:8 key9:9 key10:10 [root@lc6 ~]#
[root@lc6 ~]# for i in `seq 1 4`; do echo --memcached${i}; ./memcached-tool localhost:1121${i} dump;echo ;done
--memcached1
Dumping memcache contents
Number of buckets: 1
Number of items : 2
Dumping bucket 1 - 2 total items
add key5 768 1421107949 1
5
add key8 768 1421107949 1
8
--memcached2
Dumping memcache contents
Number of buckets: 1
Number of items : 3
Dumping bucket 1 - 3 total items
add key9 768 1421107949 1
9
add key2 768 1421107949 1
2
add key3 768 1421107949 1
3
--memcached3
Dumping memcache contents
Number of buckets: 1
Number of items : 4
Dumping bucket 1 - 4 total items
add key10 768 1421107949 2
10
add key1 768 1421107949 1
1
add key4 768 1421107949 1
4
add key6 768 1421107949 1
6
--memcached4
Dumping memcache contents
Number of buckets: 1
Number of items : 1
Dumping bucket 1 - 1 total items
add key7 768 1421107949 1
7
<?php
ini_set('memcache.hash_strategy', 'consistent');
$memcache = new Memcache;
$memcache->addServer('localhost', 11211) or die ("Could not connect");
$memcache->addServer('localhost', 11212) or die ("Could not connect");
$memcache->addServer('localhost', 11213) or die ("Could not connect");
$memcache->addServer('localhost', 11214) or die ("Could not connect");
for ($i = 1; $i <= 10; $i++) {
print 'key' . $i . ':';
print $memcache->get('key' . $i);
print ' ';
}
<?php
ini_set('memcache.hash_strategy', 'consistent');
$memcache = new Memcache;
$memcache->addServer('localhost', 11211) or die ("Could not connect");
$memcache->addServer('localhost', 11212) or die ("Could not connect");
$memcache->addServer('localhost', 11213) or die ("Could not connect");
$memcache->addServer('localhost', 11214) or die ("Could not connect");
for ($i = 1; $i <= 10; $i++) {
$memcache->set('key' . $i, $i);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment