MicronXD
MicronXD

Reputation: 2220

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 second 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... :(

Upvotes: 3

Views: 7652

Answers (4)

M_R_K
M_R_K

Reputation: 6350

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;
    }
}

Upvotes: 0

Andrew Drizgolovich
Andrew Drizgolovich

Reputation: 51

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);
   }

Upvotes: 1

MicronXD
MicronXD

Reputation: 2220

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...

Upvotes: 3

kranthi117
kranthi117

Reputation: 628

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

Upvotes: -1

Related Questions