PHP memcache - check if any server is available in pool?
Asked Answered
B

2

5

I have the following code:

$cluster['local'] = array('host' => '192.168.1.1', 'port' => '11211', 'weight' => 50);
$cluster['local2'] = array('host' => '192.168.1.2', 'port' => '11211', 'weight' => 50);

$this->memcache = new Memcache;

foreach ($this->cluster() as $cluster) {
    $this->memcache->addServer($cluster['host'], $cluster['port'], $this->persistent, $cluster['weight'], 10, 10, TRUE , 'failure' );
}

I would like to make a function that checks if any of my servers in my memcache Pool is available. How could this be done?

Barmaid answered 23/5, 2010 at 13:23 Comment(0)
P
5

You can check on a server's status by using Memcache::getServerStatus.

Parted answered 23/5, 2010 at 13:39 Comment(1)
We ended up using "memcache::getExtendedStats()" since we found that getServerStatus was a bit unreliable. getExtendedStatus seems to always give the correct state of servers in real time.Barmaid
B
2

Using fsockopen():

$timeout = 1;
$fp = fsockopen('192.168.1.1', 11211,  $errno,  $errstr,  $timeout);

if (is_resource($fp))
{
  // connection to 192.168.1.1:11211 successful
  fclose($fp);
}

else
{
  // failed to connect to 192.168.1.1:11211 within $timeout second(s).
}
Boadicea answered 23/5, 2010 at 13:38 Comment(2)
The only problem with that, is each failed server could add 1 second to the request time (about), which is exactly the kind of performance memcache is supposed to combat. I'd suggest a timeout of somewhere around 0.001 or less... It'll take some experimentation...Hollis
@ircmaxell: Agreed, that's why it's a variable. Still the Memcache::getServerStatus() seems like a better choice, I didn't knew about that method.Boadicea

© 2022 - 2024 — McMap. All rights reserved.