http://blog.csdn.net/felio/archive/2006/09/29/1303647.aspx
本文简要介绍一下安装的情况,以及PHP模块memcache使用情况:
提要:
1。安装memcached服务器端
2。安装php对memcache支持模块
3。使用memcache情况,计数器、数据压缩
4。Memcache内存的更新清理(delete flush)
5。内存超量的测试(set)
1。安装memcached服务器端
memcached安装说明(北南南北的站):
http://www.linuxsir.org/main/?q=node/184
Linux下缓存服务器的应用
作者:tonyvicky
来自:LinuxSir.Org
摘要:由于数据库存储的数据量越来越大,查询速度也就变的越来越慢,因此就有了缓存服务器应用的必要,本文是介绍Memcached的安装以及简单的使用。
本文只介绍memcached的PHP的API,想查看其他关于Memcached的API文档案,请访问 http: // www.danga.com / memcached /
目录
一、环境需求
二、下载相关软件
三、安装和配置
1 、安装Memcached
2 、安装memcache PHP模块
3 、测试脚本
四、关于本文
++++++++++++++++++++++++++++++++++++++++
正文
++++++++++++++++++++++++++++++++++++++++
一、环境需求
安装Memcached需要libevent库的支持,所以请在安装Memcached之前检查有没有安装libevent。测试环境还需要PHP的支持,本文假设PHP已经安装到 / usr / local / php目录下,也就是在编译PHP的时候使用perfix参数指定目录( -- prefix =/ usr / local / php)
二、下载相关软件
Memcached下载地址:http: // www.danga.com / memcached /
memcache PHP模块下载地址: http: // pecl.php.net / package / memcache 推荐使用1.5版
libevent 下载地址: http: // www.monkey.org /~ provos / libevent /
本文不再讲述如何安装libevent
三、安装和配置
1 、安装Memcached
root@tonyvicky: # tar vxzf memcached-1.1.12.tar.gz
root@tonyvicky: # cd memcached-1.1.12
root@tonyvicky: # ./configure --prefix=/usr/local/memcached
root@tonyvicky: # make
root@tonyvicky: # make install
安装完之后要启动服务
root@tonyvicky: # cd /usr/local/memcached/bin
root@tonyvicky: # ./memcached -d -m 50 -p 11211 -u root
参数说明 - m 指定使用多少兆的缓存空间; - p 指定要监听的端口; - u 指定以哪个用户来运行
2 、安装memcache PHP模块
root@tonyvicky: # tar vxzf memcache-1.5.tgz
root@tonyvicky: # cd memcache-1.5
root@tonyvicky: # /usr/local/php/bin/phpize
root@tonyvicky: # ./configure --enable-memcache --with-php-config=/usr/local/php/bin/php-config --with-zlib-dir
root@tonyvicky: # make
root@tonyvicky: # make install
安装完后会有类似这样的提示:
Installing shared extensions: / usr / local / php / lib / php / extensions / no - debug - non - zts - 20050922 /
把这个记住,然后修改php.ini,把
extension_dir = " ./ "
修改为
extension_dir = " /usr/local/php/lib/php/extensions/no-debug-non-zts-20050922/ "
并添加一行
extension = memcache.so
3 、测试脚本
自己写一个PHP程序测试一下吧
< ?php
$memcache = new Memcache; // 创建一个memcache对象
$memcache -> connect( ' localhost ' , 11211 ) or die ( " Could not connect " ); // 连接Memcached服务器
$memcache -> set( ' key ' , ' test ' ); // 设置一个变量到内存中,名称是key 值是test
$get_value = $memcache -> get( ' key ' ); // 从内存中取出key的值
echo $get_value;
? >
注意的是:如果你安装过程中出现错误,请看看是不是有模块没装:
autoconf
zlib (压缩数据用)
2。安装php对memcache支持模块
PHP老家:
http://cn.php.net/manual/zh/ref.memcache.php
难道, 4.3.3 都装上了吗?好像没有吧,用 4.4.4 好像都要另外装的 )Memcache Functions
简介
Memcache module provides handy procedural and object oriented interface to memcached , highly effective caching daemon , which was especially designed to decrease database load in dynamic web applications .
This module doesn ' t have native support of multiple servers, but you still can implement it yourself in your application. Establish several memcached connections, set priority level for each server etc.
More information about memcached can be found at http://www.danga.com/memcached/.
需求
This module uses functions of zlib to support on-the-fly data compression. Zlib is required to install this module.
PHP 4.3.3 or newer is required to use the memcache extension.
安装
本 PECL 扩展未绑定于 PHP 中。 进一步信息例如新版本,下载,源程序,维护者信息以及更新日志可以在此找到: http://pecl.php.net/package/memcache.
In order to use these functions you must compile PHP with Memcache support by using the --enable-memcache[=DIR] option.
Windows users will enable php_memcache.dll inside of php.ini in order to use these functions. 可以从 PHP 下载页面或者 http://snaps.php.net/ 下载此 PECL 扩展的 DLL 文件。
预定义常量
表格 1. MemCache Constants
Name Description
MEMCACHE_COMPRESSED (integer) Used to turn on-the-fly data compression on with Memcache::set(), Memcache::add() 和 Memcache::replace().
运行时配置
本扩展模块在 php.ini 中未定义任何配置选项。
资源类型
There is only one resource type used in memcache module - it ' s the link identifier for a cache server connection .
范例
例子 1 . memcache extension overview example
<? php
$memcache = new Memcache;
$memcache -> connect( ' localhost ' , 11211 ) or die ( " Could not connect " );
$version = $memcache -> getVersion();
echo " Server's version: " . $version . " <br/> " ;
$tmp_object = new stdClass;
$tmp_object -> str_attr = ' test ' ;
$tmp_object -> int_attr = 123 ;
$memcache -> set( ' key ' , $tmp_object , false , 10 ) or die ( " Failed to save data at the server " );
echo " Store data in the cache (data will expire in 10 seconds)<br/> " ;
$get_result = $memcache -> get( ' key ' );
echo " Data from the cache:<br/> " ;
var_dump ( $get_result );
?>
In the above example , an object is being saved in the cache and then retrieved back . Object and other non - scalar types are serialized before saving , so it ' s impossible to store resources (i.e. connection identifiers and others) in the cache.
目录
Memcache::add -- Add an item to the server
Memcache::close -- Close memcached server connection
Memcache::connect -- Open memcached server connection
memcache_debug -- Turn debug output on/off
Memcache::decrement -- Decrement item ' s value
Memcache :: delete -- Delete item from the server
Memcache :: flush -- Flush all existing items at the server
Memcache :: get -- Retrieve item from the server
Memcache :: getStats -- Get statistics of the server
Memcache :: getVersion -- Return version of the server
Memcache :: increment -- Increment item ' s value
Memcache::pconnect -- Open memcached server persistent connection
Memcache::replace -- Replace value of the existing item
Memcache::set -- Store data at the server
add a note User Contributed Notes
Memcache Functions
ed at me3inc dot com
27-Oct-2006 05:47
Re. Installing the memcache extension:
I had all kinds of troubles getting it hooked up, because in all of the instructions I read I never got the last, most important step - you must have a php.ini and have in it "extension=memcache.so."
So, the steps:
First - ./configure with --enable-memcache. This should show in your phpinfo() at the top (even though nothing of the memcache extension works yet).
Second:
either pecl install memcache
OR
download the source
tar -xzvf [thesourcetarball]
phpize
./configure
make
make install
Finally: Add extension=memcache.so to your php.ini. (If you don ' t have one , it should go in the root of where php is called ie ., / usr / local / lib)
Call phpinfo () and you should see a memcache section .
iliya at pisem dot net
20 - Jan - 2006 04 : 35
one more " intelligent " cache aggregator :
https : // svn.shadanakar.org/onPHP/ trunk/core/Cache/AggregateCache.class.php
can be used with several cache connectors - memcached , filesystem , etc .
(remove whitespace manually)
Gregor J . Rothfuss
22 - Nov - 2005 01 : 18
The next version will have failover . It ' s been committed three weeks ago. Usage notes here: http://www.codecomments.com/archive367-2005-10-659421.html
Ron
15-Sep-2005 04:19
An improvement to the above:
The above class will cause an error if all cache servers are down. The preferred behavior is to just have a cache miss (or take no action in the case of write operations) and return false, so the app can run in non-cached mode if all cache servers are down.
To make this happen, simply change the connection usage to look something like this in each affected function. This code is for the get() function:
$con = $this->_getConForKey($key);
if ($con === false) return false;
return $con->get($key);
Similarly, the affected code in the set() function would look like this:
$con = $this->_getConForKey($key);
if ($con === false) return false;
return $con->set($key, $var, $compress, $expire);
Modify each function accordingly, and if all of your cache servers are down, you can still function (although more slowly due to the 100% cache miss rate).
Ron
15-Sep-2005 01:20
Here is a simple memcached aggregator class which distributes the cache among multiple cache servers. If a server fails, the load is redistributed automatically. It uses persistent connections.
The constructor takes an array of arrays, with each inner array representing a server, with a ' server ' (string) attribute that is the IP addres or host name of the memcached server, and a ' port ' (int) attribute that is the port number on which memcached is running on the server.
All of the existing memcached API functions are implemented except getStats() and getVersion(), which are server-specific.
<?php
class MemcachedAggregator {
var $connections;
public function __construct($servers) {
// Attempt to establish/retrieve persistent connections to all servers.
// If any of them fail, they just don ' t get put into our list of active
// connections.
$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 ;
}
// / The following are not implemented:
// /getStats()
// /getVersion()
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 );
}
}
?>
3。使用 memcache 情况,计数器、数据压缩
使用情况一:统计
(PH P 4.3.3 or newer is required to use the memcache extension.
<?php
//访问统计
$memcache = new Memcache;
$memcache->connect('localhost', 11211) or die ("Could not connect");
if($s=$memcache->get('a')) {
$s=$s+1;
$memcache->set('a',$s);
}
else
$memcache->set('a',1);
echo '访问结果为:'.$s;
?>
其实我们可以用increment方法代替上面的做法
<?php
$memcache = new Memcache;
$memcache->connect('localhost', 11211) or die ("Could not connect");
if($s=$memcache->increment('a',1)) {
echo $s;
}
else
$memcache->set('a',1);
?>
数据压缩:
<?php
$memcache = new Memcache;
$memcache->connect('localhost', 11211) or die ("Could not connect");
$test=(str_repeat('jetwong',100000));
$memcache->set('b',($test));
?>
使用压缩:
<?php
$memcache = new Memcache;
$memcache->connect('localhost', 11211) or die ("Could not connect");
$test=(str_repeat('jetwong',100000));
$memcache->set('b',($test),MEMCACHE_COMPRESSED);
?>
使用情况说明:
前台比较 |
目前内存 |
总共读取 |
总共写入 |
压缩前 |
700085 |
700081 |
416 |
压缩后 |
1131 |
1125 |
13 |
可能看到压缩后明显占用内存少了不少
4。Memcache内存的更新清理(delete flush)
<?php
$memcache = new Memcache;
$memcache->connect('localhost', 11211) or die ("Could not connect");
/*设置值*/
$status = $memcache->getStats();
echo '设置前内存使用情况'.$status['bytes'].'<br>';
echo '设置后';
for($i=0;$i<9;$i++) {
$memcache->set('b'.$i,rand(1,99));
echo '<br>'.$i.'->'.$memcache->get('b'.$i);
}
/*查看设置的值*/
$status = $memcache->getStats();
echo 'delete前内存使用情况'.$status['bytes'].'<br>';
echo '<br>开始delete';
for($i=0;$i<9;$i++) {
$memcache->delete('b'.$i);
echo '<br>'.$i.'->'.$memcache->get('b'.$i);
}
/*查看flush使用的情况*/
$status = $memcache->getStats();
echo '使用flush前内存使用情况'.$status['bytes'].'<br>';
echo '使用flush情况:';
for($i=0;$i<9;$i++) {
$memcache->set('b'.$i,rand(1,99));
echo '<br>'.$i.'->'.$memcache->get('b'.$i);
}
$memcache->flush();
echo 'flush之后:';
for($i=0;$i<9;$i++) {
echo '<br>'.$i.'->'.$memcache->get('b'.$i);
}
$status = $memcache->getStats();
echo 'flush后内存使用情况'.$status['bytes'].'<br>';
?>
5。内存超量的测试(set)
我们把内存设为2M
./memcached -d -m 2 -p 11211 -u root
<?php
$memcache = new Memcache;
$memcache->connect('localhost', 11211) or die ("Could not connect");
//600K左右
$test1= str_repeat('jetlee',100000);
//600K左右
$test2= str_repeat('jetlee',100000);
//600K左右
$test3= str_repeat('李连杰',200000);
//600K左右
$test4= str_repeat('连杰李',100000);
//200K
$test5= file_get_contents('http://img.pconline.com.cn/images/photoblog/2988177/20068/4/1154688770042_mthumb.JPG');
$test6= file_get_contents('http://img.pconline.com.cn/images/photoblog/1767557/20069/28/1159417108902_mthumb.jpg');
for($i=1;$i<=6;$i++) {
$j='test'.$i;
if($memcache->set($j,$$j)) {
echo $j.'->设置成功<br>';
$status = $memcache->getStats();
echo '内存:'.$status['bytes'].'<br>';
}
else {
echo $j.'->设置失败<br>';
}
}
?>
执行结果:
test1->设置成功
内存:600042
test2->设置成功
内存:1200084
test3->设置失败
test4->设置成功
内存:1200084
test5->设置失败
test6->设置失败
刚好印证我们的计算,不过20万的repeat为什么会失败,不是太了解,,,,,,
总结:
示例:
<?
//设置篇
if($data = $memcache->get('k',$v)) {
//显示我们的数据
}
else {
$data = get_from_database; //得到数据源
if(!$memcache->set('k',$data), MEMCACHE_COMPRESSED) //开始设置
log(); //不成功,记录失败信息
}
?>
-----------OVER-----------
Trackback: http://tb.blog.csdn.net/TrackBack.aspx?PostId=1303647