memcached的php客户端操作类一
<?php
//
// +---------------------------------------------------------------------------+
// | memcached client, php |
// +---------------------------------------------------------------------------+
// | copyright (c) 2003 ryan t. dean <[email protected]> |
// | all rights reserved. |
// | |
// | redistribution and use in source and binary forms, with or without |
// | modification, are permitted provided that the following conditions |
// | are met: |
// | |
// | 1. redistributions of source code must retain the above copyright |
// | notice, this list of conditions and the following disclaimer. |
// | 2. redistributions in binary form must reproduce the above copyright |
// | notice, this list of conditions and the following disclaimer in the |
// | documentation and/or other materials provided with the distribution. |
// | |
// | this software is provided by the author ``as is'' and any express or |
// | implied warranties, including, but not limited to, the implied warranties |
// | of merchantability and fitness for a particular purpose are disclaimed. |
// | in no event shall the author be liable for any direct, indirect, |
// | incidental, special, exemplary, or consequential damages (including, but |
// | not limited to, procurement of substitute goods or services; loss of use, |
// | data, or profits; or business interruption) however caused and on any |
// | theory of liability, whether in contract, strict liability, or tort |
// | (including negligence or otherwise) arising in any way out of the use of |
// | this software, even if advised of the possibility of such damage. |
// +---------------------------------------------------------------------------+
// | author: ryan t. dean <[email protected]> |
// | heavily influenced by the perl memcached client by brad fitzpatrick. |
// | permission granted by brad fitzpatrick for relicense of ported perl |
// | client logic under 2-clause bsd license. |
// +---------------------------------------------------------------------------+
//
// $tcanet$
//
/**
* this is the php client for memcached - a distributed memory cache daemon.
* more information is available at http://www.danga.com/memcached/
*
* usage example:
*
* require_once 'memcached.php';
*
* $mc = new memcached(array(
* 'servers' => array('127.0.0.1:10000',
* array('192.0.0.1:10010', 2),
* '127.0.0.1:10020'),
* 'debug' => false,
* 'compress_threshold' => 10240,
* 'persistant' => true));
*
* $mc->add('key', array('some', 'array'));
* $mc->replace('key', 'some random string');
* $val = $mc->get('key');
*
* @author ryan t. dean <[email protected]>
* @package memcached-client
* @version 0.1.2
*/
// {{{ requirements
// }}}
// {{{ constants
// {{{ flags
/**
* flag: indicates data is serialized
*/
define("memcache_serialized", 1<<0);
/**
* flag: indicates data is compressed
*/
define("memcache_compressed", 1<<1);
// }}}
/**
* minimum savings to store data compressed
*/
define("compression_savings", 0.20);
// }}}
// {{{ class memcached
/**
* memcached client class implemented using (p)fsockopen()
*
* @author ryan t. dean <[email protected]>
* @package memcached-client
*/
class memcached
{
// {{{ properties
// {{{ public
/**
* command statistics
*
* @var array
* @access public
*/
var $stats;
// }}}
// {{{ private
/**
* cached sockets that are connected
*
* @var array
* @access private
*/
var $_cache_sock;
/**
* current debug status; 0 - none to 9 - profiling
*
* @var boolean
* @access private
*/
var $_debug;
/**
* dead hosts, assoc array, 'host'=>'unixtime when ok to check again'
*
* @var array
* @access private
*/
var $_host_dead;
/**
* is compression available?
*
* @var boolean
* @access private
*/
var $_have_zlib;
/**
* do we want to use compression?
*
* @var boolean
* @access private
*/
var $_compress_enable;
/**
* at how many bytes should we compress?
*
* @var interger
* @access private
*/
var $_compress_threshold;
/**
* are we using persistant links?
*
* @var boolean
* @access private
*/
var $_persistant;
/**
* if only using one server; contains ip:port to connect to
*
* @var string
* @access private
*/
var $_single_sock;
/**
* array containing ip:port or array(ip:port, weight)
*
* @var array
* @access private
*/
var $_servers;
/**
* our bit buckets
*
* @var array
* @access private
*/
var $_buckets;
/**
* total # of bit buckets we have
*
* @var interger
* @access private
*/
var $_bucketcount;
/**
* # of total servers we have
*
* @var interger
* @access private
*/
var $_active;
// }}}
// }}}
// {{{ methods
// {{{ public functions
// {{{ memcached()
/**
* memcache initializer
*
* @param array $args associative array of settings
*
* @return mixed
* @access public
*/
function memcached ($args)
{
$this->set_servers($args['servers']);
$this->_debug = $args['debug'];
$this->stats = array();
$this->_compress_threshold = $args['compress_threshold'];
$this->_persistant = isset($args['persistant']) ? $args['persistant'] : false;
$this->_compress_enable = true;
$this->_have_zlib = function_exists("gzcompress");
$this->_cache_sock = array();
$this->_host_dead = array();
}
// }}}
// {{{ add()
/**
* adds a key/value to the memcache server if one isn't already set with
* that key
*
* @param string $key key to set with data
* @param mixed $val value to store
* @param interger $exp (optional) time to expire data at
*
* @return boolean
* @access public
*/
function add ($key, $val, $exp = 0)
{
return $this->_set('add', $key, $val, $exp);
}
// }}}
// {{{ decr()
/**
* decriment a value stored on the memcache server
*
* @param string $key key to decriment
* @param interger $amt (optional) amount to decriment
*
* @return mixed false on failure, value on success
* @access public
*/
function decr ($key, $amt=1)
{
return $this->_incrdecr('decr', $key, $amt);
}
// }}}
// {{{ delete()
/**
* deletes a key from the server, optionally after $time
*
* @param string $key key to delete
* @param interger $time (optional) how long to wait before deleting
*
* @return boolean true on success, false on failure
* @access public
*/
function delete ($key, $time = 0)
{
if (!$this->_active)
return false;
$sock = $this->get_sock($key);
if (!is_resource($sock))
return false;
$key = is_array($key) ? $key[1] : $key;
$this->stats['delete']++;
$cmd = "delete $key $time/r/n";
if(!fwrite($sock, $cmd, strlen($cmd)))
{
$this->_dead_sock($sock);
return false;
}
$res = trim(fgets($sock));
if ($this->_debug)
printf("memcache: delete %s (%s)/n", $key, $res);
if ($res == "deleted")
return true;
return false;
}
// }}}
// {{{ disconnect_all()
/**
* disconnects all connected sockets
*
* @access public
*/
function disconnect_all ()
{
foreach ($this->_cache_sock as $sock)
fclose($sock);
$this->_cache_sock = array();
}
// }}}
// {{{ enable_compress()
/**
* enable / disable compression
*
* @param boolean $enable true to enable, false to disable
*
* @access public
*/
function enable_compress ($enable)
{
$this->_compress_enable = $enable;
}
// }}}
// {{{ forget_dead_hosts()
/**
* forget about all of the dead hosts
*
* @access public
*/
function forget_dead_hosts ()
{
$this->_host_dead = array();
}
// }}}
// {{{ get()
/**
* retrieves the value associated with the key from the memcache server
*
* @param string $key key to retrieve
*
* @return mixed
* @access public
*/
function get ($key)
{
if (!$this->_active)
return false;
$sock = $this->get_sock($key);
if (!is_resource($sock))
return false;
$this->stats['get']++;
$cmd = "get $key/r/n";
if (!fwrite($sock, $cmd, strlen($cmd)))
{
$this->_dead_sock($sock);
return false;
}
$val = array();
$this->_load_items($sock, $val);
if ($this->_debug)
foreach ($val as $k => $v)
printf("memcache: sock %s got %s => %s/r/n", $sock, $k, $v);
return $val[$key];
}
// }}}
// {{{ get_multi()
/**
* get multiple keys from the server(s)
*
* @param array $keys keys to retrieve
*
* @return array
* @access public
*/
function get_multi ($keys)
{
if (!$this->_active)
return false;
$this->stats['get_multi']++;
foreach ($keys as $key)
{
$sock = $this->get_sock($key);
if (!is_resource($sock)) continue;
$key = is_array($key) ? $key[1] : $key;
if (!isset($sock_keys[$sock]))
{
$sock_keys[$sock] = array();
$socks[] = $sock;
}
$sock_keys[$sock][] = $key;
}
// send out the requests
foreach ($socks as $sock)
{
$cmd = "get";
foreach ($sock_keys[$sock] as $key)
{
$cmd .= " ". $key;
}
$cmd .= "/r/n";
if (fwrite($sock, $cmd, strlen($cmd)))
{
$gather[] = $sock;
} else
{
$this->_dead_sock($sock);
}
}
// parse responses
$val = array();
foreach ($gather as $sock)
{
$this->_load_items($sock, $val);
}
if ($this->_debug)
foreach ($val as $k => $v)
printf("memcache: got %s => %s/r/n", $k, $v);
return $val;
}
// }}}
// {{{ incr()
/**
* increments $key (optionally) by $amt
*
* @param string $key key to increment
* @param interger $amt (optional) amount to increment
*
* @return interger new key value?
* @access public
*/
function incr ($key, $amt=1)
{
return $this->_incrdecr('incr', $key, $amt);
}
// }}}
// {{{ replace()
/**
* overwrites an existing value for key; only works if key is already set
*
* @param string $key key to set value as
* @param mixed $value value to store
* @param interger $exp (optional) experiation time
*
* @return boolean
* @access public
*/
function replace ($key, $value, $exp=0)
{
return $this->_set('replace', $key, $value, $exp);
}
// }}}
// {{{ run_command()
/**
* passes through $cmd to the memcache server connected by $sock; returns
* output as an array (null array if no output)
*
* note: due to a possible bug in how php reads while using fgets(), each
* line may not be terminated by a /r/n. more specifically, my testing
* has shown that, on freebsd at least, each line is terminated only
* with a /n. this is with the php flag auto_detect_line_endings set
* to falase (the default).
*
* @param resource $sock socket to send command on
* @param string $cmd command to run
*
* @return array output array
* @access public
*/
function run_command ($sock, $cmd)
{
if (!is_resource($sock))
return array();
if (!fwrite($sock, $cmd, strlen($cmd)))
return array();
while (true)
{
$res = fgets($sock);
$ret[] = $res;
if (preg_match('/^end/', $res))
break;
if (strlen($res) == 0)
break;
}
return $ret;
}
// }}}
// {{{ set()
/**
* unconditionally sets a key to a given value in the memcache. returns true
* if set successfully.
*
* @param string $key key to set value as
* @param mixed $value value to set
* @param interger $exp (optional) experiation time
*
* @return boolean true on success
* @access public
*/
function set ($key, $value, $exp=0)
{
return $this->_set('set', $key, $value, $exp);
}
// }}}
// {{{ set_compress_threshold()
/**
* sets the compression threshold
*
* @param interger $thresh threshold to compress if larger than
*
* @access public
*/
function set_compress_threshold ($thresh)
{
$this->_compress_threshold = $thresh;
}
// }}}
// {{{ set_debug()
/**
* sets the debug flag
*
* @param boolean $dbg true for debugging, false otherwise
*
* @access public
*
* @see memcahced::memcached
*/
function set_debug ($dbg)
{
$this->_debug = $dbg;
}
// }}}
// {{{ set_servers()
/**
* sets the server list to distribute key gets and puts between
*
* @param array $list array of servers to connect to
*
* @access public
*
* @see memcached::memcached()
*/
function set_servers ($list)
{
$this->_servers = $list;
$this->_active = count($list);
$this->_buckets = null;
$this->_bucketcount = 0;
$this->_single_sock = null;
if ($this->_active == 1)
$this->_single_sock = $this->_servers[0];
}
// }}}
// }}}
// {{{ private methods
// {{{ _close_sock()
/**
* close the specified socket
*
* @param string $sock socket to close
*
* @access private
*/
function _close_sock ($sock)
{
$host = array_search($sock, $this->_cache_sock);
fclose($this->_cache_sock[$host]);
unset($this->_cache_sock[$host]);
}
// }}}
// {{{ _connect_sock()
/**
* connects $sock to $host, timing out after $timeout
*
* @param interger $sock socket to connect
* @param string $host host:ip to connect to
* @param float $timeout (optional) timeout value, defaults to 0.25s
*
* @return boolean
* @access private
*/
function _connect_sock (&$sock, $host, $timeout = 0.25)
{
list ($ip, $port) = explode(":", $host);
if ($this->_persistant == 1)
{
$sock = @pfsockopen($ip, $port, $errno, $errstr, $timeout);
} else
{
$sock = @fsockopen($ip, $port, $errno, $errstr, $timeout);
}
if (!$sock)
return false;
return true;
}
// }}}
// {{{ _dead_sock()
/**
* marks a host as dead until 30-40 seconds in the future
*
* @param string $sock socket to mark as dead
*
* @access private
*/
function _dead_sock ($sock)
{
$host = array_search($sock, $this->_cache_sock);
list ($ip, $port) = explode(":", $host);
$this->_host_dead[$ip] = time() + 30 + intval(rand(0, 10));
$this->_host_dead[$host] = $this->_host_dead[$ip];
unset($this->_cache_sock[$host]);
}
// }}}
// {{{ get_sock()
/**
* get_sock
*
* @param string $key key to retrieve value for;
*
* @return mixed resource on success, false on failure
* @access private
*/
function get_sock ($key)
{
if (!$this->_active)
return false;
if ($this->_single_sock !== null)
return $this->sock_to_host($this->_single_sock);
$hv = is_array($key) ? intval($key[0]) : $this->_hashfunc($key);
if ($this->_buckets === null)
{
foreach ($this->_servers as $v)
{
if (is_array($v))
{
for ($i=0; $i<$v[1]; $i++)
$bu[] = $v[0];
} else
{
$bu[] = $v;
}
}
$this->_buckets = $bu;
$this->_bucketcount = count($bu);
}
$realkey = is_array($key) ? $key[1] : $key;
for ($tries = 0; $tries<20; $tries++)
{
$host = $this->_buckets[$hv % $this->_bucketcount];
$sock = $this->sock_to_host($host);
if (is_resource($sock))
return $sock;
$hv += $this->_hashfunc($tries . $realkey);
}
return false;
}
// }}}
// {{{ _hashfunc()
/**
* creates a hash interger based on the $key
*
* @param string $key key to hash
*
* @return interger hash value
* @access private
*/
function _hashfunc ($key)
{
$hash = 0;
for ($i=0; $i<strlen($key); $i++)
{
$hash = $hash*33 + ord($key[$i]);
}
return $hash;
}
// }}}
// {{{ _incrdecr()
/**
* perform increment/decriment on $key
*
* @param string $cmd command to perform
* @param string $key key to perform it on
* @param interger $amt amount to adjust
*
* @return interger new value of $key
* @access private
*/
function _incrdecr ($cmd, $key, $amt=1)
{
if (!$this->_active)
return null;
$sock = $this->get_sock($key);
if (!is_resource($sock))
return null;
$key = is_array($key) ? $key[1] : $key;
$this->stats[$cmd]++;
if (!fwrite($sock, "$cmd $key $amt/r/n"))
return $this->_dead_sock($sock);
stream_set_timeout($sock, 1, 0);
$line = fgets($sock);
if (!preg_match('/^(/d+)/', $line, $match))
return null;
return $match[1];
}
// }}}
// {{{ _load_items()
/**
* load items into $ret from $sock
*
* @param resource $sock socket to read from
* @param array $ret returned values
*
* @access private
*/
function _load_items ($sock, &$ret)
{
while (1)
{
$decl = fgets($sock);
if ($decl == "end/r/n")
{
return true;
} elseif (preg_match('/^value (/s+) (/d+) (/d+)/r/n$/', $decl, $match))
{
list($rkey, $flags, $len) = array($match[1], $match[2], $match[3]);
$bneed = $len+2;
$offset = 0;
while ($bneed > 0)
{
$data = fread($sock, $bneed);
$n = strlen($data);
if ($n == 0)
break;
$offset += $n;
$bneed -= $n;
$ret[$rkey] .= $data;
}
if ($offset != $len+2)
{
// something is borked!
if ($this->_debug)
printf("something is borked! key %s expecting %d got %d length/n", $rkey, $len+2, $offset);
unset($ret[$rkey]);
$this->_close_sock($sock);
return false;
}
$ret[$rkey] = rtrim($ret[$rkey]);
if ($this->_have_zlib && $flags & memcache_compressed)
$ret[$rkey] = gzuncompress($ret[$rkey]);
if ($flags & memcache_serialized)
$ret[$rkey] = unserialize($ret[$rkey]);
} else
{
if ($this->_debug)
print("error parsing memcached response/n");
return 0;
}
}
}
// }}}
// {{{ _set()
/**
* performs the requested storage operation to the memcache server
*
* @param string $cmd command to perform
* @param string $key key to act on
* @param mixed $val what we need to store
* @param interger $exp when it should expire
*
* @return boolean
* @access private
*/
function _set ($cmd, $key, $val, $exp)
{
if (!$this->_active)
return false;
$sock = $this->get_sock($key);
if (!is_resource($sock))
return false;
$this->stats[$cmd]++;
$flags = 0;
if (!is_scalar($val))
{
$val = serialize($val);
$flags |= memcache_serialized;
if ($this->_debug)
printf("client: serializing data as it is not scalar/n");
}
$len = strlen($val);
if ($this->_have_zlib && $this->_compress_enable &&
$this->_compress_threshold && $len >= $this->_compress_threshold)
{
$c_val = gzcompress($val, 9);
$c_len = strlen($c_val);
if ($c_len < $len*(1 - compress_savings))
{
if ($this->_debug)
printf("client: compressing data; was %d bytes is now %d bytes/n", $len, $c_len);
$val = $c_val;
$len = $c_len;
$flags |= memcache_compressed;
}
}
if (!fwrite($sock, "$cmd $key $flags $exp $len/r/n$val/r/n"))
return $this->_dead_sock($sock);
$line = trim(fgets($sock));
if ($this->_debug)
{
if ($flags & memcache_compressed)
$val = 'compressed data';
printf("memcache: %s %s => %s (%s)/n", $cmd, $key, $val, $line);
}
if ($line == "stored")
return true;
return false;
}
// }}}
// {{{ sock_to_host()
/**
* returns the socket for the host
*
* @param string $host host:ip to get socket for
*
* @return mixed io stream or false
* @access private
*/
function sock_to_host ($host)
{
if (isset($this->_cache_sock[$host]))
return $this->_cache_sock[$host];
$now = time();
list ($ip, $port) = explode (":", $host);
if (isset($this->_host_dead[$host]) && $this->_host_dead[$host] > $now ||
isset($this->_host_dead[$ip]) && $this->_host_dead[$ip] > $now)
return null;
if (!$this->_connect_sock($sock, $host))
return $this->_dead_sock($host);
// do not buffer writes
stream_set_write_buffer($sock, 0);
$this->_cache_sock[$host] = $sock;
return $this->_cache_sock[$host];
}
// }}}
// }}}
// }}}
}
// }}}
?>
新闻热点
疑难解答