Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is memcache.hash_strategy for?

Tags:

php

memcached


I wonder why there is a memcache.hash_strategy php.ini setting. The manual says:

Controls which strategy to use when mapping keys to servers. Set this value to consistent to enable consistent hashing which allows servers to be added or removed from the pool without causing keys to be remapped. Setting this value to standard results in the old strategy being used.

But isn't a programmer himself maps key to servers? Here is some pseudo-code:

$memcacheServerList = array('host1', 'host2', 'host3');
$key = 'my_key';
$memcacheServerIndex = crc32($key) % sizeof($memcacheServerList);

$memcache = new Memcache();  
$memcache->connect($memcacheServerList[$memcacheServerIndex], 11211);
$memcache->add($key, 'this is value');

What do I miss?

like image 828
Vadim Samokhin Avatar asked Oct 24 '22 19:10

Vadim Samokhin


1 Answers

You are using some old examples. The modern way to use memcache is as such:

$servers = array(
    "10.1.1.1",
    "10.1.1.2",
    "10.1.1.3",
);

$m = new Memcache();

foreach($servers as $server) {
    $m->addServer ( $server );
}

$m->add($key, 'this is value');

Now the memcache code will now use its hashing method to determine the server. You can use two options. Consistent hashing will reduce the effect of removing a server from the list. Where as traditional hashing is basically the code you have above. You can find more on that at http://www.last.fm/user/RJ/journal/2007/04/10/rz_libketama_-_a_consistent_hashing_algo_for_memcache_clients

like image 125
brianlmoon Avatar answered Oct 27 '22 09:10

brianlmoon