这是一个简单的 memcached 聚合器类,它将缓存分布到多个缓存服务器上。如果服务器出现故障,负载会自动重新分配。它使用持久连接。
构造函数接受一个数组数组,每个内部数组代表一个服务器,具有一个“server”(字符串)属性,即 memcached 服务器的 IP 地址或主机名,以及一个“port”(整数)属性,即 memcached 在服务器上运行的端口号。
所有现有的 memcached API 函数都已实现,除了 getStats() 和 getVersion(),它们是特定于服务器的。
<?php
class MemcachedAggregator {
var $connections;
public function __construct($servers) {
$this->connections = array();
for ($i = 0, $n = count($servers); $i < $n; $i++) {
$server = $servers[$i];
$con = memcache_pconnect($server['host'], $server['port']);
if (!($con == false)) {
$this->connections[] = $con;
}
}
}
private function _getConForKey($key) {
$hashCode = 0;
for ($i = 0, $len = strlen($key); $i < $len; $i++) {
$hashCode = (int)(($hashCode*33)+ord($key[$i])) & 0x7fffffff;
}
if (($ns = count($this->connections)) > 0) {
return $this->connections[$hashCode%$ns];
}
return false;
}
public function debug($on_off) {
$result = false;
for ($i = 0; $i < count($connections); $i++) {
if ($this->connections[$i]->debug($on_off)) $result = true;
}
return $result;
}
public function flush() {
$result = false;
for ($i = 0; $i < count($connections); $i++) {
if ($this->connections[$i]->flush()) $result = true;
}
return $result;
}
public function get($key) {
if (is_array($key)) {
$dest = array();
foreach ($key as $subkey) {
$val = get($subkey);
if (!($val === false)) $dest[$subkey] = $val;
}
return $dest;
} else {
return $this->_getConForKey($key)->get($key);
}
}
public function set($key, $var, $compress=0, $expire=0) {
return $this->_getConForKey($key)->set($key, $var, $compress, $expire);
}
public function add($key, $var, $compress=0, $expire=0) {
return $this->_getConForKey($key)->add($key, $var, $compress, $expire);
}
public function replace($key, $var, $compress=0, $expire=0) {
return $this->_getConForKey($key)->replace
($key, $var, $compress, $expire);
}
public function delete($key, $timeout=0) {
return $this->_getConForKey($key)->delete($key, $timeout);
}
public function increment($key, $value=1) {
return $this->_getConForKey($key)->increment($key, $value);
}
public function decrement($key, $value=1) {
return $this->_getConForKey($key)->decrement($key, $value);
}
}
?>