Memcached::getServerByKey

(PECL memcached >= 0.1.0)

Memcached::getServerByKeyMap a key to a server

Description

public Memcached::getServerByKey(string $server_key): array|false

Memcached::getServerByKey() returns the server that would be selected by a particular server_key in all the Memcached::*ByKey() operations.

Parameters

server_key

The key identifying the server to store the value on or retrieve it from. Instead of hashing on the actual key for the item, we hash on the server key when deciding which memcached server to talk to. This allows related items to be grouped together on a single server for efficiency with multi operations.

Return Values

Returns an array containing three keys of host, port, and weight on success or false on failure. Use Memcached::getResultCode() if necessary.

Examples

Example #1 Memcached::getServerByKey() example

<?php
$m
= new Memcached();
$m->addServers(array(
array(
'mem1.domain.com', 11211, 40),
array(
'mem2.domain.com', 11211, 40),
array(
'mem3.domain.com', 11211, 20),
));

$m->setOption(Memcached::OPT_LIBKETAMA_COMPATIBLE, true);

var_dump($m->getServerByKey('user'));
var_dump($m->getServerByKey('log'));
var_dump($m->getServerByKey('ip'));
?>

The above example will output something similar to:

array(3) {
  ["host"]=>
  string(15) "mem3.domain.com"
  ["port"]=>
  int(11211)
  ["weight"]=>
  int(20)
}
array(3) {
  ["host"]=>
  string(15) "mem2.domain.com"
  ["port"]=>
  int(11211)
  ["weight"]=>
  int(40)
}
array(3) {
  ["host"]=>
  string(15) "mem2.domain.com"
  ["port"]=>
  int(11211)
  ["weight"]=>
  int(40)
}
add a note

User Contributed Notes 2 notes

up
5
zhaoyong dot lc at gmail dot com
11 years ago
The parameter server_key is very confusing, it's not a server key for MemCached Server, but it's key,in key-value pair which you stored in server.

<?php
$m
= new Memcached;
$m->addServers(array(
array(
'127.0.0.1',11212),
array(
'127.0.0.1',11211)
));
for(
$i=0;$i<10;$i++){
$key = 'key_'.$i;
$m->add($key, 1);
}
for(
$i=0;$i<10;$i++) {
$key = 'key_'.$i;
$arr = $m->getServerByKey($key);
echo (
$key.":\t".$arr['port']."\n");
}
?>

key_0: 11212
key_1: 11211
key_2: 11212
key_3: 11212
key_4: 11212
key_5: 11211
key_6: 11211
key_7: 11212
key_8: 11212
key_9: 11211
up
1
morphles
8 years ago
Just to clarify (as documentation of memcached, even for C lib, frankly is quite lacking), $server_key is hashed using same method as regular keys for values (I checked C source, as again docs......). So you should be able to see where set($key, $value) goes by using getServerByKey($key) with same key. This can be useful if one does not wish to bother with using/has no need to use *ByKey functions, but still want to know which servers are/should be used with regular keys, for implementing fallback or failure reporting.
To Top