How does addServer method of PHP Memcache/Memcached work?

1k Views Asked by At

I'm currently running PHP Memcache on Apache server. Since Memcache and Memcached have similar inner workings this question is about both of them.

I was wondering through the addServer method of memcached here and the second comment on the user section is this:

Important to not call ->addServers() every run -- only call it if no servers exist (check getServerList() ); otherwise, since addServers() does not check for dups, it will let you add the same server again and again and again, resultings in hundreds if not thousands of connections to the MC daemon. Specially when using FastCGI.

It is not clear what is meant by "every run". Does it mean calling addServer within the script multiple times or within multiple requests by different users/remote clients? Because consider the following script:

<?php
    $memcache_obj = new \Memcache;
    //$memcache_obj->connect('localhost', 11211); --> each time new connection, not recommended
    $memcache_obj->addServer('localhost', 11211,true,1,1,15,true,function($hostname,$port){
        //echo("There was a problem with {$hostname} at {$port}");
        die;
    });
    print_r($memcache_obj->getExtendedStats());
?>

If as client, I make an xmlhttp request to above script, I will get something like this:

Array
(
    [localhost:11211] => Array
        (
            [pid] => 12308
            [uptime] => 3054538123
            ....

So far so good, if I uncomment the addServer part and execute like this:

<?php
    $memcache_obj = new \Memcache;
    print_r($memcache_obj->getExtendedStats());
?>

Then I get this:

<br />
<b>Warning</b>:  MemcachePool::getserverstatus(): No servers added to 
memcache connection in <b>path/to/php</b> on line <b>someLineNumber</b><br />

So obviously at least a server has to be added when the php script is called by the remote client. Then which of the following is true here:

  • we should be careful not to call `addServer`` within the same PHP script too many times. (I am inclined to understand it this way)
  • we should be careful not to call addServer among multiple requests (For example 2 user's calling same php script etc. I can't seem to figure out how this can ever be done.)
1

There are 1 best solutions below

0
On

You do have to add the server once, else you will get this error. As the comment suggests you should use getServerList() to check if the servers have been added already and add them if they are not present:

<?php
    $memcache_obj = new \Memcache;
    //$memcache_obj->connect('localhost', 11211); --> each time new connection, not recommended
    if (!memcache_obj->getServerList()){
        $memcache_obj->addServer('localhost', 11211,true,1,1,15,true,function($hostname,$port){
            //echo("There was a problem with {$hostname} at {$port}");
            die;
        });
    }
    print_r($memcache_obj->getExtendedStats());
?>