上一篇PHP 中使用 Memcached 作缓存(3)- 使用 memcached扩展 byKey系列方法讲了 PHP memcached 扩展的基本用法,这一篇我们将以下举例说明以下 byKey 系列函数的用法。
byKey 系列函数主要是为了解决在多台服务器的情况下,将一些值存取指定服务器的问题。
<?php $oMemCached = new \Memcached(); $oMemCached->addServer('127.0.0.1', 11211, 10); $oMemCached->addServer('127.0.0.1', 11212, 10); $oMemCached->addServer('127.0.0.1', 11213, 10); print_r($oMemCached->getVersion()); print_r($oMemCached->getServerList()); print_r($oMemCached->getServerByKey('tpl')); print_r($oMemCached->getServerByKey('config')); print_r($oMemCached->getServerByKey('sql')); print_r($oMemCached->getServerByKey('zpz')); $oMemCached->setByKey('zpz', 'name', 'zpz'); $oMemCached->setByKey('zpz', 'age', '1000'); $oMemCached->setByKey('zpz', 'male', 'yes'); echo 'name : ', $oMemCached->getByKey('zpz', 'name'), "\n"; echo 'age : ', $oMemCached->getByKey('zpz', 'age'), "\n"; echo 'male : ', $oMemCached->getByKey('zpz', 'male'), "\n"; $oMemCached->setByKey('tpl', 'index', 'index.tpl.php'); $oMemCached->setByKey('tpl', 'head', 'head.tpl.php'); $oMemCached->setByKey('tpl', 'foot', 'foot.tpl.php'); $oMemCached->getDelayedByKey('tpl', array('index', 'head', 'foot'), false, function(){ print_r(func_get_args()); });
输出:
Array ( [127.0.0.1:11211] => 1.4.14 [127.0.0.1:11212] => 1.4.14 [127.0.0.1:11213] => 1.4.14 ) Array ( [0] => Array ( [host] => 127.0.0.1 [port] => 11211 [weight] => 10 ) [1] => Array ( [host] => 127.0.0.1 [port] => 11212 [weight] => 10 ) [2] => Array ( [host] => 127.0.0.1 [port] => 11213 [weight] => 10 ) ) Array ( [host] => 127.0.0.1 [port] => 11211 [weight] => 10 ) Array ( [host] => 127.0.0.1 [port] => 11212 [weight] => 10 ) Array ( [host] => 127.0.0.1 [port] => 11211 [weight] => 10 ) Array ( [host] => 127.0.0.1 [port] => 11213 [weight] => 10 ) name : zpz age : 1000 male : yes Array ( [0] => Memcached Object ( ) [1] => Array ( [key] => index [value] => index.tpl.php ) ) Array ( [0] => Memcached Object ( ) [1] => Array ( [key] => head [value] => head.tpl.php ) ) Array ( [0] => Memcached Object ( ) [1] => Array ( [key] => foot [value] => foot.tpl.php ) )