2012-09-19 41 views
1

根據php.net,memcache_connect() should return TRUE on success or FALSE on failure。因此,我想如果我改變我的緩存服務器地址到一個不存在的地址下面的代碼應該工作就算了,但事實並非如此:使用PHP檢查是否存在memcache連接?

$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 

有誰知道我可以如何設置這個簡單的布爾值?

+1

地址仍需要有效。嘗試** http://google.com**。服務器應嘗試連接,但不會找到memcache服務器並返回FALSE。儘管取決於域如何處理請求,但可能無法正常工作。 – donutdan4114

+1

你爲什麼說它不起作用? $ memcache將是真或假 - $ this-> connect應該是什麼?你期待一個對象,或布爾? (請注意,我會在一個答案中發佈更好的方法,但不知道爲什麼上述「dopesn't工作」) – Robbie

+0

@ donutdan4114我想這個代碼來處理的情況下,如果地址是無效的。例如,如果服務器停機。如果發生這種情況,我想在本地主機上緩存。 –

回答

1

根據評論,不知道爲什麼上述不起作用,但有一個更好的方式來處理這個。

如果「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'); 
    } 
} 
+0

我看到基本上一個用戶可以觸發重寫配置文件,以便後續用戶(5分鐘後)將不會超時? –

+1

這就是主意。不是一個「理想」的情況,但比每次等待超時要快很多(毫秒)。重寫配置是一個選項(不是我建議的,但它會工作)。我建議只是緩存緩存工作與否,並採取替代措施,如果沒有。 – Robbie

0

我發現部分工作的php.net's Memcache documentation的解決方案。意思是,顯示給用戶的錯誤被抑制,但如果緩存服務器不存在,你仍然需要等待很長的超時時間。

這裏是我的代碼如下:

$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'; 
    }  
0

我使用此代碼進行檢查連接

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