Memcached PHP module: How can you tell if the connection failed?
in a php file, I have:
<?php
$m = new Memcached();
echo get_class($m);
echo "<br>";
echo $m->addServer('192.168.1.77', 11211, 1);
$m->set("foo", "bar");
?>
when run, around a half se开发者_C百科cond later, I get:
Memcached
1
If I stop memcached, after about 5 seconds, I get:
Memcached
1
I was expecting something more like...
Memcached
0
How do you know if you've successfully hit the memcached server or not? I was fully expecting it to be as simple as a return value from addServer... :(
This is kinda what I was looking for: Memcached::getStats();
So, I wrote:
add_memcached_server($m, $addr, $port)
{
$m->addServer($addr,$port);
$statuses = $m->getStats();
return isset($statuses[$addr.":".$port]);
}
works like a charm...
Answer is
/**
* check for connection was established
* @param resource $m
* @param string $host
* @param int $port
* @access public
* @return bool
*/
function memConnected($m, $host, $port = 11211)
{
$statuses = $m->getStats();
return (isset($statuses[$host.":".$port]) and $statuses[$host.":".$port]["pid"] > 0);
}
This is how I did it
/**
* Add memcached server
* @param String $new_ New Memcahed
* @param String $addr Address
* @param String $port Port
* @return boolean
*/
function add_memcached_server($new_, $addr, $port)
{
$new_->addServer($addr,$port);
$statuses = $new_->getStats();
if($statuses[$addr.':'.$port]['uptime']<1){
return false;
}else{
return true;
}
}
http://php.net/memcache.addserver states that
When using this method (as opposed to Memcache::connect() and Memcache::pconnect()) the network connection is not established until actually needed.
so there is no way addServer
knows if the network connection is established
use http://php.net/memcache.connect instead
精彩评论