1. Introduction
The memcache module is an efficient daemon that provides procedural programs and object-oriented convenient interfaces for memory caching, especially for reducing database access when designing dynamic web programs.
memcache also provides processing for communication conversations (session_handler).
More information about the Memcache module can be found at http://www.danga.com/memcached/.
1.1. Memcache configuration item list in php.ini
memcache configuration item list in php.ini
Name |
Default value |
Modifiable range |
Change log |
memcache.allow_failover |
"1" |
PHP_INI_ALL |
Available since memcache 2.0.2. |
memcache.max_failover_attempts |
"20" |
PHP_INI_ALL | Available since memcache 2.1.0. |
memcache. chunk_size |
"8192" |
PHP_INI_ALL |
Available since memcache 2.0.2. |
memcache.default_port |
"11211" |
PHP_INI_ALL |
Available since memcache 2.0.2. |
memcache.hash_strategy | "standard" |
PHP_INI_ALL |
Available since memcache 2.2.0. 0. |
session.save_handler |
" files" |
PHP_INI_ALL |
Supported since memcache 2.1.2 |
session.save_path |
"" |
PHP_INI_ALL |
Supported since memcache 2.1.2 |
| For further details and definitions of PHP_INI_* constants, see PHP manual php.ini configuration options. | 1.2. The following is a brief explanation of the configuration items |
memcache.allow_failover |
Boolean
Whether to transparently failover to other servers when errors occur (note: failover is a verb).
memcache.max_failover_attempts integerDefine the server’s number class settings and get data, only used in conjunction with memcache.allow_failover.
memcache.chunk_size
integerThe data will be divided into chunks of the specified size (chunk_size) for transmission. The smaller this value (chunk_size), the more write operation requests will be required. If other For unexplained slowdowns, try increasing this value to 32768.
memcache.default_portstringWhen connecting to the memcache server, if no port is specified this default tcp port will be used.
memcache.hash_strategy string controls which strategy is used when mapping keys to servers. Setting this value consistently enables the hash algorithm to be used consistently and will not be remapped when the server accepts additions or removals of variables from the pool. Setting this value gives standard results when the old strategy is used.
memcache.hash_function stringControl which hsah function is applied to the key mapping process to the server. The default value "crc32" uses the CRC32 algorithm, while "fnv" indicates the use of the FNV-1a algorithm.
session.save_handler string Set this value to memcache to determine the use of memcache for communication conversation processing (session handler).
session.save_path string Define the delimiter symbol for each server link used for call storage, for example: "tcp://host1:11211, tcp://host2:11211".
Each server link can contain parameters accepted by the server, similar to using Memcache::addServer() to add a server, for example: "tcp://host1:11211?persistent=1&weight=1&timeout=1& retry_interval=15".
1.3. memcache constant list memcache constant list
name type description
MEMCACHE_COMPRESSED
integer |
is used to adjust when using Mem cache::set(), Memcache::add () and Memcache::replace() several functions. |
|
MEMCACHE_HAVE_SESSION
integer |
If the communication session handler is allowed to use its value is 1, otherwise the value is 0. |
|
2Memcache Functions function list
2.1.Memcache::connect
2.1.1. Description
bool Memcache::connect ( string $host [, int $port [, int $timeout ]] )
Connect to the memcache server
2.1.2. Parameters
$host(string) Server domain name or ip
$port(int) Server tcp port number, the default value is 11211
$timeout The expiration time of the connection memcache process. Think twice when modifying its default value of 1, so as not to lose all the advantages of memcache caching and cause the connection to change. Very slowly.
2.1.3. Return value
Return true if successful, false if failed
2.1.4. Example
php
/* procedural API */$memcache_obj = memcache_connect('memcache_host', 11211);
/* OO API */$memcache = new Memcache;
$memcache->connect('memcache_host', 11211);
?>
2.2.Memcache::pconnect
2.2.1.Description
bool Memcache::pconnect ( string$host [ ,int $port [,int $timeout ]] )
Connect to the server in constant connection mode
2.2.2.Parameters
$ host(string) server domain name or ip
$port(int) server tcp port number, the default value is 11211
$timeout the expiration time of the connection memcache process, think twice when modifying its default value of 1, so as not to lose everything The advantage of memcache caching causes the connection to become very slow.
2.2.3. Return value
Return true if successful, false if failed
2.2.4.Example
php/*procedural API */$memcache_obj= memcache_pconnect('memcache_host', 11211); /* OO API */ $memcache_obj = newMemcache;$memcache_obj->pconnect('memcache_host', 11211);?>
2.3.Memcache::close
2.3.1.Description
bool Memcache::close ( void )
Close object (right Constant connection does not work)
2.3.2. Return value
Returns true if successful, false if failed
2.3.3. Example
php
/* procedural API */$memcache_obj = memcache_connect(‘memcache_host‘, 11211);
/* do something here .. */
memcache_close($memcache_obj);
/* OO API */$memcache_obj = new Memcache;
$memcache_obj->connect(‘memcache_host‘, 11211);
/* do something here .. */$memcache_obj->close();
?>
2.4.Memcache::addServer
2.4.1.说明
bool Memcache::addServer ( string $host [, int $port [, bool $persistent [, int $weight [, int $timeout [, int $retry_interval [, bool $status [, callback $failure_callback ]]]]]]] )
向对象添加一个服务器(注:addServer没有连接到服务器的动作,所以在memcache进程没有启动的时候,执行addServer成功也会返回true)
2.4.2.参数
host 服务器域名或 IP
port 端口号,默认为 11211
persistent 是否使用常连接,默认为 TRUE
weight 权重,在多个服务器设置中占的比重
timeout 连接服务器失效的秒数,修改默认值 1 时要三思,有可能失去所有缓存方面的优势导致连接变得很慢
retry_interval 服务器连接失败时的重试频率,默认是 15 秒一次,如果设置为 -1 将禁止自动重试,当扩展中加载了 dynamically via dl() 时,无论本参数还是常连接设置参数都会失效。
每一个失败的服务器在失效前都有独自的生存期,选择后端请求时会被跳过而不服务于请求。一个过期的连接将成功的重新连接或者被标记为失败的连接等待下一次 重试。这种效果就是说每一个 web server 的子进程在服务于页面时的重试连接都跟他们自己的重试频率有关。
status 控制服务器是否被标记为 online,设置这个参数为 FALSE 并设置 retry_interval 为 -1 可以使连接失败的服务器被放到一个描述不响应请求的服务器池子中,对这个服务器的请求将失败,接受设置为失败服务器的设置,默认参数为 TRUE,代表该服务器可以被定义为 online。
failure_callback 失败时的回调函数,函数的两个参数为失败服务器的 hostname 和 port
2.4.3.返回值
成功返回 TRUE,失败返回 FALSE。
注:在测试addServer函数的时候我们主要测试了其参数retry_interval和status
2.4.4.范例
2.4.4.1.retry_interval参数的测试
php
$mem = new Memcache;
$is_add = $mem-> addServer('localhost', 11211, true, 1, 1, 15, true); // retrt_interval=15$is_set = $mem-> set('key1', ' People's Republic of China');
?>
In the above example, if the localhost server goes down or the memcache daemon crashes, 15 seconds will elapse from when the connection to the server fails when executing the request. It will automatically retry to connect to the server, but it will not connect to the server within these 15 seconds. That is, as long as there is a request, it will try to connect to the server within 15 seconds, but each server connection retry is independent. For example, I added two servers at once, one is localhost and the other is 172.16.100.60. Counting from the time when their respective connections failed, they will connect to their respective servers every 15 seconds as long as there is a request for their respective servers.
2.4.4.2. Combination of retry_interval and status
php
$mem = new Memcache ;
$is_add =$mem->addServer('localhost', 11211,true, 1, 1,-1, false); // retrt_interval=-1, status=false $is_set = $ mem&- & gt; Set ('Key1', ' The People's Republic of China ');
? =false In this case, the server that failed to connect will be placed in a pool that does not respond to requests, so it will have no impact on the key allocation algorithm. Whether it will immediately return an error failure or failover depends on memcache. The setting of allow_failover will fail and return false when executing set, add, replace, get and other requests, even if the memcache process is running normally. 2.4.4.3. Test of status parameter
In addition to being used in combination with retry_interval, the use of status alone will affect the results obtained by the function memcache::getServerStatuWhether the memcache process is running normally or crashes, status is true When the memcache process is running normally, the result of getServerStatus is true, otherwise it is false. However, when the memcache process is running normally, it has no effect on set, add, replace, get and other functions. 2.5.Memcache::add
2.5.1.Description
bool Memcache
::
add (
string
$key , mixed $var [, int $flag [, int $expire ]] ) Add a data to be cached if as this If the key of cached data does not exist on the server yet, 2.5.2. Parameter key use using using with use using
‐ out out out out off out off off ’ s ’ out through out out out out out out outmb out outmb out outmb out outmb out out out out out out out out out out out out out out out together past s i ,, , 2.5.2. parameters key It is serialized and stored, and its value is up to 1M
flag Whether to use zlib compression? When flag=MEMCACHE_COMPRESSED, zlib compression will not be used when the data is very small. Only when the data reaches a certain size, zlib compression will be performed on the data. (There is no specific test data to compress the minimum value)
expire Expiration time, 0 means never expires, you can use the unix timestamp format or the number of seconds from the current time, when set to seconds, it cannot be greater than 2592000 (30 days)
2.5.3. Return value
Returns TRUE on success, FALSE on failure. If the key already exists, memcache:;add() behaves similarly to memcache::set in other respects
2.5.4. Example
php$memcache_obj=memcache_connect("localhost ",11211); /* procedural API */memcache_add($memcache_obj, 'var_key', 'test variable', FALSE, 30);/* OO API */$memcache_obj->add('var_key', 'test variable' , FALSE,30);?>
2.6.Memcache::replace
2.6.1. Description
bool Memcache ::replace (string $key , mixed$var [ , int $flag [ ,int $expire ]] )
Replace the cache variable content of a specified existing key
2.6.2. Parameter
key Its length cannot exceed 250 characters VAR value, the integer will be stored directly, and other types will be serialized. The maximum value is whether 1m
flag is compressed by ZLIB. Using zlib compression, the data is zlib compressed only when the data reaches a certain size. (There is no specific test data to compress the minimum value)
expire Expiration time, 0 means never expires, you can use the unix timestamp format or the number of seconds from the current time, when set to seconds, it cannot be greater than 2592000 (30 days)
2.6.3. Return value
Returns TRUE if successful, and FALSE if failed.
2.6.4.Example
php
$memcache_obj = memcache_connect(‘memcache_host‘, 11211);
/* procedural API */
memcache_replace($memcache_obj, "test_key", "some variable", FALSE, 30);
/* OO API */$memcache_obj->replace("test_key", "some variable", FALSE, 30);
?>
2.7.Memcache::set
2.7.1.说明
bool Memcache::set ( string $key , mixed $var [, int $flag [, int $expire ]] )
设置一个指定 key 的缓存变量内容
2.7.2.参数
key 缓存数据的键, 其长度不能超过250个字符
var 值,整型将直接存储,其他类型将被序列化存储,其值最大为1M
flag 是否使用 zlib 压缩 ,当flag=MEMCACHE_COMPRESSED的时侯,数据很小的时候不会采用zlib压缩,只有数据达到一定大小才对数据进行zlib压缩。(没有具体的测试数据进行压缩的最小值是多少)
expire 过期时间,0 为永不过期,可使用 unix 时间戳格式或距离当前时间的秒数,设为秒数时不能大于 2592000(30 天)
2.7.3.返回值
成功返回 TRUE,失败返回 FALSE。
2.7.4.范例
php/* procedural API *//* connect to memcached server */$memcache_obj = memcache_connect(‘memcache_host‘, 11211);/*set value of item with key ‘var_key‘using 0 as flag value, compression is not usedexpire time is 30 second*/memcache_set($memcache_obj, ‘var_key‘, ‘some variable‘, 0, 30);echo memcache_get($memcache_obj, ‘var_key‘);?>
php/* OO API */$memcache_obj = new Memcache;/* connect to memcached server */$memcache_obj->connect(‘memcache_host‘, 11211);/*set value of item with key ‘var_key‘, using on-the-fly compressionexpire time is 50 seconds*/$memcache_obj->set(‘var_key‘, ‘some really big variable‘, MEMCACHE_COMPRESSED, 50);echo $memcache_obj->get(‘var_key‘);?>
2.8.Memcache::get
2.8.1.说明
string Memcache::get ( string $key [, int &$flags ] )
array Memcache::get ( array $keys [, array &$flags ] )
获取某个 key 的变量缓存值
2.8.2.参数
key 缓存值的键
flags 如果是传址某个变量,获取缓存值被set或是add的flag结果将被存于该变量
2.8.3.返回值
返回缓存的指定 key 的变量内容或者是在失败或该变量的值不存在时返回 FALSE
如果传出的key的数组中的key都不存在,返回的结果是一个空数组,反之则返回key与缓存值相关联的关联数组
2.8.4.范例
php
/* procedural API */$memcache_obj = memcache_connect(‘memcache_host‘, 11211);
$var = memcache_get($memcache_obj, ‘some_key‘);
/* OO API */$memcache_obj = new Memcache;
$memcache_obj->connect(‘memcache_host‘, 11211);
$var = $memcache_obj->get(‘some_key‘);
/*
You also can use array of keys as a parameter.
If such item wasn‘t found at the server, the result
array simply will not include such key.
*//* procedural API */$memcache_obj = memcache_connect(‘memcache_host‘, 11211);
$var = memcache_get($memcache_obj, Array(‘some_key‘, ‘another_key‘));
//如果some_key,another_key不存在 $var = array();
//如果some_key,another_key存在 $var = array(‘some_key‘=>‘缓存值‘, ‘another_key‘=>‘缓存值‘);
/* OO API */$memcache_obj = new Memcache;
$memcache_obj->connect(‘memcache_host‘, 11211);
$var = $memcache_obj->get(Array(‘some_key‘, ‘second_key‘));
?>
2.9.Memcache::delete
2.9.1.说明
bool Memcache::delete ( string $key [, int $timeout ] )
删除某一个变量的缓存
2.9.2.参数
key 缓存的键 键值不能为null和‘’,当它等于前面两个值的时候php会有警告错误。
timeout 删除这项的时间,如果它等于0,这项将被立刻删除反之如果它等于30秒,那么这项被删除在30秒内
2.9.3.返回值
成功返回 TRUE,失败返回 FALSE。
2.9.4.范例
php
/* procedural API */$memcache_obj=memcache_connect('memcache_host' , 11211);
/* after 10 seconds item will be deleted by the server */
memcache_delete($memcache_obj, 'key_to_delete' ,10);
/* OO API */$memcache_obj = newMemcache;
$memcache_obj ->connect('memcache_host', 11211);
$memcache_obj->delete('key_to_delete', 10) ;
?>
2.10.Memcache::flush
2.10.1.Description
bool Memcache::flush ( void )
Clear all cache contents, not true Deleting the cached content simply expires the cache of all variables, causing the content in the memory to be rewritten
2.10.2. Return value
Returns TRUE if successful, and FALSE if failed.
2.10.3.Example
php
/* procedural API */$memcache_obj =memcache_connect('memcache_host ',11211);
memcache_flush($memcache_obj);
/* OO API */ $memcache_obj = new Memcache;
$memcache_obj->connect('memcache_host', 11211);
$mem cache_obj->flush( );
?> Memcache
::getExtendedStats ([ string
$type[,int $slabid[,int $limit]]] ) Get all server extensions Static information 2.11.2. Parameter type Static information type. Valid values include {reset, malloc, maps, cachedump, slabs, items, sizes}. This optional parameter is agreed according to certain rules to facilitate developers to view different The title entered by the category information slabid is used to jointly set the cache heap to a valid slice into the heap according to the specified type. The cache heap is bound to the server by the command and is strictly used for debugging purposes. limit is used to jointly set the cache heap according to the specified type to the size limited to the heap by the number entered. The default value is 100 2.11.3 .Return valueReturns a two-dimensional array of static information extended by the server, and returns FALSE on failure2.11.4.范例
php
$memcache_obj = new Memcache;
$memcache_obj->addServer(‘memcache_host‘, 11211);
$memcache_obj->addServer(‘failed_host‘, 11211);
$stats = $memcache_obj->getExtendedStats(); print_r($stats);
?>
输出结果
Array(
[memcache_host:11211] => Array(
[pid] => 3756
[uptime] => 603011
[time] => 1133810435
[version] => 1.1.12
[rusage_user] => 0.451931
[rusage_system] => 0.634903
[curr_items] => 2483
[total_items] => 3079
[bytes] => 2718136
[curr_connections] => 2
[total_connections] => 807
[connection_structures] => 13
[cmd_get] => 9748
[cmd_set] => 3096
[get_hits] => 5976
[get_misses] => 3772
[bytes_read] => 3448968
[bytes_written] => 2318883
[limit_maxbytes] => 33554432
),
[failed_host:11211] =>
)
2.12.Memcache::getStats
2.12.1.说明
array Memcache::getStats ([ string $type [, int $slabid [, int $limit ]]] )
获取最后添加服务器静态信息
2.12.2.参数
type 静态信息类型,有效值包括{reset, malloc, maps, cachedump, slabs, items, sizes},依照一定规则协议这个可选参数是为了方便开发人员查看不同类别的信息而输入的标题
slabid 用于按指定类型联合设置 cache 堆为有效的片到堆中。缓存堆被被命令绑定到服务器上并被严格的用于调试用途
limit 用于按指定类型联合设置 cache 堆为输入的数字所限制的大小到堆,默认值为 100
2.12.3.返回值
返回一个服务器静态信息数组,失败时返回 FALSE
2.13.Memcache::getServerStatus
2.13.1. Description
int Memcache::getServerStatus (string$host[,int $port ] )
Get the corresponding server information by entering the host and port
2.13.2. Parameters
host server domain name or IP
port port number, the default is 11211
2.13.3. Return value
Return to server status , 0 is failure, otherwise a non-0 number is returned
2.13.4. Example
php
/* OO API */ $memcache = new Memcache;
$memcache->addServer('memcache_host', 11211);
echo $memcache->getServerStatus('memcache_host', 11211);
/* procedural API */$memcache = memcache_connect('memcache_host',11211);
echomemcache_get_server_status($memcache, 'memcache_host', 11211);
?>
::getVersion (void)
Get the version number information of the server 2.14.2. Return value Returns the version number string of the server if successful, FALSE if failed 2.14.3. Example
php/* OO API */$memcache =
newMemcache;
$memcache->connect(' memcache_host',11211);echo
$memcache->getVersion(); /* procedural API */
$memcache =memcache_connect('memcache_host',
11211);echomemcache_get_version( $memcache);?>
2.15.Memcache::setCompressThresholdbool Memcache
::setCompressThreshold ( int
$threshold [,
float $ min_savings ])Set the compression limit2.15.2. Parameterthreshold Set the minimum value of the variable length that controls automatic compressionmin_saving specifies the minimum compression ratio, the value must be between 0 - 1 between, the default is 0.2, which represents a compression ratio of 20% 2.15.3. Return value Returns TRUE if successful, and FALSE if failed. 2.15.4.范例
php
/* OO API */$memcache_obj = new Memcache;
$memcache_obj->addServer(‘memcache_host‘, 11211);
$memcache_obj->setCompressThreshold(20000, 0.2);
/* procedural API */$memcache_obj = memcache_connect(‘memcache_host‘, 11211);
memcache_set_compress_threshold($memcache_obj, 20000, 0.2);
?>
2.16.Memcache::setServerParams
2.16.1.说明
bool Memcache::setServerParams ( string $host [, int $port [, int $timeout [, int $retry_interval [, bool $status [, callback $failure_callback ]]]]] )
Memcache version 2.1.0 后增加的函数,运行时设置服务器参数
2.16.2.参数
host 服务器域名或 IP
port 端口号,默认为 11211
timeout 超时连接失效的秒数,修改默认值 1 时要三思,有可能失去所有缓存方面的优势导致连接变得很慢
retry_interval 服务器连接失败时的重试频率,默认是 15 秒一次,如果设置为 -1 将禁止自动重试,当扩展中加载了 dynamically via dl() 时,无论本参数还是常连接设置参数都会失效。 每一个失败的服务器在失效前都有独自的生存期,选择后端请求时会被跳过而不服务于请求。一个过期的连接将成功的重新连接或者被标记为失败的连接等待下一次 重试。这种效果就是说每一个 web server 的子进程在服务于页面时的重试连接都跟他们自己的重试频率有关。
status 控制服务器是否被标记为 online,设置这个参数为 FALSE 并设置 retry_interval 为 -1 可以使连接失败的服务器被放到一个描述不响应请求的服务器池子中,对这个服务器的请求将失败,接受设置为失败服务器的设置,默认参数为 TRUE,代表该服务器可以被定义为 online。
failure_callback 失败时的回调函数,函数的两个参数为失败服务器的 hostname 和 port
2.16.3.返回值
成功返回 TRUE,失败返回 FALSE。
2.16.4.范例
php
function _callback_memcache_failure($host, $port)
{
print "memcache ‘$host:$port‘ failed";
}
/* OO API */$memcache = new Memcache;
// Add the server in offline mode$memcache->addServer(‘memcache_host‘, 11211, FALSE, 1, 1, -1, FALSE);
// Bring the server back online$memcache->setServerParams(‘memcache_host‘, 11211, 1, 15, TRUE, ‘_callback_memcache_failure‘);
/* procedural API */$memcache_obj = memcache_connect(‘memcache_host‘, 11211);
memcache_set_server_params($memcache_obj, ‘memcache_host‘, 11211, 1, 15, TRUE, ‘_callback_memcache_failure‘);
?>
2.17.Memcache::increment
2.17.1.说明
int Memcache::increment ( string $key [, int $value ] )
给指定 key 的缓存变量一个增值,如果该变量不是数字时不会被转化为数字,这个增值将会加到该变量原有的数字之上,变量不存在不会新增变量,对于压缩存储的变量不要使用本函数因为相应的取值方法会失败。
2.17.2.参数
key 缓存值的键
var 值,整型将直接存储,其他类型将被序列化存储
2.17.3.返回值
成功返回新的变量值,失败返回 FALSE。
2.17.4.范例
php
/* procedural API */$memcache_obj = memcache_connect(‘memcache_host‘, 11211);
/* increment counter by 2 */$current_value = memcache_increment($memcache_obj, ‘counter‘, 2);
/* OO API */$memcache_obj = new Memcache;
$memcache_obj->connect(‘memcache_host‘, 11211);
/* increment counter by 3 */$current_value = $memcache_obj->increment(‘counter‘, 3);
?>
2.18.Memcache::decrement
2.18.2.Description
int Memcache::decrement ( string$key [ , int $value ] )
Give the cache variable of the specified key a decrement value. Similar to the increment operation, this value will be subtracted from the original variable, and the value of the item will be After subtraction after conversion to a number, the value of the new item will not be less than 0. Do not use this function for compressed stored variables because the corresponding value method will fail.
2.18.2. Parameter
key key of cache value
var value, integer type will be stored directly, other types will be serialized and stored
2.18.3. Return value
Return new variable value successfully, fail Return FALSE.
2.18.4.Example
php
/* procedural API */$memcache_obj =memcache_connect('memcache_host ',11211);
/*decrement item by 2*/$new_value= memcache_decrement($memcache_obj, 'test_item',2);
/* OO API */$memcache_obj= new Memcache;
$ memcache_obj->connect('memcache_host', 11211);
/* decrement item by 3* /$new_value= $memcache_obj->decrement('test_item', 3);
?>
2.19.memcache_debug
2.19.1. Description
bool memcache_debug ( bool $on_off )
Set whether the memcache debugger is turned on, the value is TRUE or FALSE. Affected by whether the --enable-debug option is used during php installation, this function will only return TRUE if used, and will always return FALSE in other cases.
2.19.2. Parameter
on_off sets whether the debugging mode is on, TRUE is on, FALSE is off
2.19.3. Return value
php returns TRUE if the --enable-debug option is used during installation, otherwise will return FALSE.
The above is a summary of PHP's memcache, including aspects of it. I hope it will be helpful to friends who are interested in PHP tutorials.