使用 PHP 检查是否存在内存缓存连接



根据 php.net,memcache_connect()应该在成功时返回TRUE,在失败时返回FALSE。因此,我认为即使我将缓存服务器地址更改为不存在的地址,以下代码也应该有效,但它没有:

    $memcache=memcache_connect('myCacheServer.com', 11211);
    if($memcache){
        $this->connect=$memcache;
    }
    else{
        $memcache=memcache_connect('localhost', 11211);
        $this->connect=$memcache;
    }

这是我收到的错误消息:

Message: memcache_connect(): php_network_getaddresses: getaddrinfo failed: Temporary 
failure in name resolution

有谁知道我还能如何设置这个简单的布尔值?

根据评论,不确定为什么上述方法不起作用,但有一种更好的方法来解决这个问题。

如果无法连接到"myCacheServer.com",则每次最多可能需要 30 秒才能超时。然后在超时后,您将回退到本地主机 - 但如果每次需要等待 30 秒,则运行 memcached 没有多大意义。

我建议将服务器放在配置文件中,或者基于已知值进行驾驶 - 类似于

if (isset($_SERVER['HTTP_HOST']) && strpos($_SERVER['HTTP_HOST'], 'localhost') ) !== false) {
    define('MEMCAHCED_SERVER', 'localhost');
    define('MEMCAHCED_PORT', '11211');
} else {
    // assume live - alwways have live as the fallback
    define('MEMCAHCED_SERVER', 'myCacheHost.com');
    define('MEMCAHCED_PORT', '11211');
}
$memcache=memcache_connect(MEMCAHCED_SERVER, MEMCAHCED_PORT);   
// Set the status to true or false.
$this->connect=$memcache;

然后,为了满足您的需求(如果您预计远程服务器不可用),我会将此事实存储在服务器上的文件中。它有点不合时宜,但会节省你的时间。

// Before calling memcache connect
if (file_exists(MyFlagFile) and filemtime(MyFlagFile) > time() - 600) {
     // Do Not Use Memcached as it failed within hte last 5 minutes
} else {
     // Try to use memcached again
     if (!$memcache) {
         // Write a file to the server with the time, stopping more tries for the next 5 minutes
         file_put_contents(MyFlagFile, 'Failed again');
     }
 }

我从php.net的Memcache文档中找到了一个部分有效的解决方案。这意味着,向用户显示的错误将被禁止显示,但如果缓存服务器不存在,您仍然需要等待很长时间的超时。

这是我的代码:

    $host='myCacheServer.com';
    $port=11211;
    $memcache = new Memcache();
    $memcache->addServer($host, $port);
    $stats = @$memcache->getExtendedStats();
    $available = (bool) $stats["$host:$port"];
    if ($available && @$memcache->connect($host, $port)){
            $this->connect=$memcache;
           // echo 'true';
    }
    else{
            $host='localhost';
            $memcache->addServer($host, $port);
            $this->connect=$memcache;
            //echo 'false';
    }    

我使用此代码检查连接

function checkConnection()
{
    try {
        $client = $this->initClient();
        $data = @$client->getVersion();
    } catch (Exception $e) {
        $data = false;
    }
    return !empty($data);
}

最新更新