Vadim Samokhin
Vadim Samokhin

Reputation: 3456

What is memcache.hash_strategy for?


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?

Upvotes: 5

Views: 3544

Answers (1)

brianlmoon
brianlmoon

Reputation: 324

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

Upvotes: 3

Related Questions