2010-05-23 49 views
5

我有以下代码:PHP memcache - 检查池中是否有服务器可用?

$cluster['local'] = array('host' => '192.168.1.1', 'port' => '11211', 'weight' => 50); 
$cluster['local2'] = array('host' => '192.168.1.2', 'port' => '11211', 'weight' => 50); 

$this->memcache = new Memcache; 

foreach ($this->cluster() as $cluster) { 
    $this->memcache->addServer($cluster['host'], $cluster['port'], $this->persistent, $cluster['weight'], 10, 10, TRUE , 'failure'); 
} 

我想提出来检查,如果在我的memcache池中的任何我的服务器的可用功能。这怎么能做到?

回答

5

您可以通过使用Memcache::getServerStatus对服务器的状态检查。

+0

不错的方法,+1! =) – 2010-05-23 13:59:45

+2

我们最终使用“memcache :: getExtendedStats()”,因为我们发现getServerStatus有点不可靠。 getExtendedStatus似乎总是实时地提供服务器的正确状态。 – Industrial 2010-05-23 16:24:20

2

使用fsockopen()

$timeout = 1; 
$fp = fsockopen('192.168.1.1', 11211, $errno, $errstr, $timeout); 

if (is_resource($fp)) 
{ 
    // connection to 192.168.1.1:11211 successful 
    fclose($fp); 
} 

else 
{ 
    // failed to connect to 192.168.1.1:11211 within $timeout second(s). 
} 
+3

唯一的问题是,每个失败的服务器可能会在请求时间(约)上增加1秒,这正是性能缓存的本意。我建议在0.001或更少的地方暂停......这需要一些实验...... – ircmaxell 2010-05-23 13:44:00

+1

@ircmaxell:同意,这就是为什么它是一个变量。仍然'Memcache :: getServerStatus()'似乎是一个更好的选择,我不知道这种方法。 – 2010-05-23 13:58:41