[英]Check if memcache connection exists using 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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.