memcached安装+php使用手记

http://blog.csdn.net/felio/archive/2006/09/29/1303647.aspx

本文简要介绍一下安装的情况,以及PHP模块memcache使用情况:

提要:
1。安装memcached服务器端
2。安装phpmemcache支持模块
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 、安装memcachePHP模块
3 、测试脚本
四、关于本文


++++++++++++++++++++++++++++++++++++++++
正文
++++++++++++++++++++++++++++++++++++++++


一、环境需求
安装Memcached需要libevent库的支持,所以请在安装Memcached之前检查有没有安装libevent。测试环境还需要PHP的支持,本文假设PHP已经安装到
/ usr / local / php目录下,也就是在编译PHP的时候使用perfix参数指定目录( -- prefix =/ usr / local / php)

二、下载相关软件

Memcached下载地址:http:
// www.danga.com / memcached /
memcachePHP模块下载地址:http:
// pecl.php.net / package / memcache推荐使用1.5版
libevent下载地址:http:
// www.monkey.org /~ provos / libevent /

本文不再讲述如何安装libevent

三、安装和配置

1 、安装Memcached


root@tonyvicky:
# tarvxzfmemcached-1.1.12.tar.gz
root@tonyvicky: # cdmemcached-1.1.12
root@tonyvicky: # ./configure--prefix=/usr/local/memcached
root@tonyvicky: # make
root@tonyvicky: # makeinstall

安装完之后要启动服务


root@tonyvicky:
# cd/usr/local/memcached/bin
root@tonyvicky: # ./memcached-d-m50-p11211-uroot

参数说明
- m指定使用多少兆的缓存空间; - p指定要监听的端口; - u指定以哪个用户来运行

2 、安装memcachePHP模块


root@tonyvicky:
# tarvxzfmemcache-1.5.tgz
root@tonyvicky: # cdmemcache-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: # makeinstall

安装完后会有类似这样的提示:


Installingsharedextensions:
/ 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
= newMemcache; // 创建一个memcache对象
$memcache
-> connect( ' localhost ' , 11211 ) or die( " Couldnotconnect " ); // 连接Memcached服务器
$memcache
-> set( ' key ' , ' test ' ); // 设置一个变量到内存中,名称是key值是test
$get_value
= $memcache -> get( ' key ' ); // 从内存中取出key的值
echo$get_value;
?
>

注意的是:如果你安装过程中出现错误,请看看是不是有模块没装:
autoconf
zlib (
压缩数据用)

2。安装phpmemcache支持模块
PHP
老家:
http://cn.php.net/manual/zh/ref.memcache.php

MemcacheFunctions
简介
Memcachemoduleprovideshandyproceduraland
object oriented interface tomemcached , highlyeffectivecachingdaemon , whichwasespeciallydesignedtodecreasedatabaseloadindynamicwebapplications .

Thismoduledoesn
' thavenativesupportofmultipleservers,butyoustillcanimplementityourselfinyourapplication.Establishseveralmemcachedconnections,setprioritylevelforeachserveretc.

Moreinformationaboutmemcachedcanbefoundathttp://www.danga.com/memcached/.

需求
Thismoduleusesfunctionsofzlibtosupporton-the-flydatacompression.Zlibisrequiredtoinstallthismodule.

PHP4.3.3ornewerisrequiredtousethememcacheextension.

安装
本PECL扩展未绑定于PHP中。进一步信息例如新版本,下载,源程序,维护者信息以及更新日志可以在此找到:http://pecl.php.net/package/memcache.

InordertousethesefunctionsyoumustcompilePHPwithMemcachesupportbyusingthe--enable-memcache[=DIR]option.

Windowsuserswillenablephp_memcache.dllinsideofphp.iniinordertousethesefunctions.可以从PHP下载页面或者http://snaps.php.net/下载此PECL扩展的DLL文件。

预定义常量
表格1.MemCacheConstants

NameDescription
MEMCACHE_COMPRESSED(integer)Usedtoturnon-the-flydatacompressiononwithMemcache::set(),Memcache::add()和Memcache::replace().

运行时配置
本扩展模块在php.ini中未定义任何配置选项。

资源类型
Thereisonlyoneresourcetypeusedinmemcachemodule-it
' sthelinkidentifier for acacheserverconnection .

范例
例子
1 . memcacheextensionoverviewexample

<? php

$memcache = new Memcache;
$memcache -> connect( ' localhost ' , 11211 )or die ( " Couldnotconnect " );

$version = $memcache -> getVersion();
echo " Server'sversion: " . $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 ( " Failedtosavedataattheserver " );
echo " Storedatainthecache(datawillexpirein10seconds)<br/> " ;

$get_result = $memcache -> get( ' key ' );
echo " Datafromthecache:<br/> " ;

var_dump ( $get_result );

?>



Intheaboveexample
, an object isbeingsavedinthecacheandthenretrievedback . Object andothernon - scalartypesareserializedbeforesaving , soit ' simpossibletostoreresources(i.e.connectionidentifiersandothers)inthecache.

目录
Memcache::add--Addanitemtotheserver
Memcache::close--Closememcachedserverconnection
Memcache::connect--Openmemcachedserverconnection
memcache_debug--Turndebugoutputon/off
Memcache::decrement--Decrementitem
' svalue
Memcache
:: delete -- Deleteitemfromtheserver
Memcache
:: flush -- Flush allexistingitemsattheserver
Memcache
:: get -- Retrieveitemfromtheserver
Memcache
:: getStats -- Getstatisticsoftheserver
Memcache
:: getVersion -- Return versionoftheserver
Memcache
:: increment -- Incrementitem ' svalue
Memcache::pconnect--Openmemcachedserverpersistentconnection
Memcache::replace--Replacevalueoftheexistingitem
Memcache::set--Storedataattheserver



addanoteUserContributedNotes
MemcacheFunctions
edatme3incdotcom
27-Oct-200605:47
Re.Installingthememcacheextension:

Ihadallkindsoftroublesgettingithookedup,becauseinalloftheinstructionsIreadInevergotthelast,mostimportantstep-youmusthaveaphp.iniandhaveinit"extension=memcache.so."

So,thesteps:
First-./configurewith--enable-memcache.Thisshouldshowinyourphpinfo()atthetop(eventhoughnothingofthememcacheextensionworksyet).

Second:
eitherpeclinstallmemcache
OR
downloadthesource
tar-xzvf[thesourcetarball]
phpize
./configure
make
makeinstall

Finally:Addextension=memcache.sotoyourphp.ini.(Ifyoudon
' thaveone , itshouldgointherootofwherephpiscalledie ., / usr / local / lib)

Call
phpinfo ()andyoushouldseeamemcachesection .
iliyaatpisemdotnet
20 - Jan - 2006 04 : 35
onemore
" intelligent " cacheaggregator :
https
: // svn.shadanakar.org/onPHP/trunk/core/Cache/AggregateCache.class.php
canbeusedwithseveralcacheconnectors - memcached , filesystem , etc .
(removewhitespacemanually)
GregorJ
. Rothfuss
22 - Nov - 2005 01 : 18
The
next versionwillhavefailover . It ' sbeencommittedthreeweeksago.Usagenoteshere:http://www.codecomments.com/archive367-2005-10-659421.html
Ron
15-Sep-200504:19
Animprovementtotheabove:

Theaboveclasswillcauseanerrorifallcacheserversaredown.Thepreferredbehavioristojusthaveacachemiss(ortakenoactioninthecaseofwriteoperations)andreturnfalse,sotheappcanruninnon-cachedmodeifallcacheserversaredown.

Tomakethishappen,simplychangetheconnectionusagetolooksomethinglikethisineachaffectedfunction.Thiscodeisfortheget()function:

$con=$this->_getConForKey($key);
if($con===false)returnfalse;
return$con->get($key);

Similarly,theaffectedcodeintheset()functionwouldlooklikethis:
$con=$this->_getConForKey($key);
if($con===false)returnfalse;
return$con->set($key,$var,$compress,$expire);

Modifyeachfunctionaccordingly,andifallofyourcacheserversaredown,youcanstillfunction(althoughmoreslowlyduetothe100%cachemissrate).
Ron
15-Sep-200501:20
Hereisasimplememcachedaggregatorclasswhichdistributesthecacheamongmultiplecacheservers.Ifaserverfails,theloadisredistributedautomatically.Itusespersistentconnections.

Theconstructortakesanarrayofarrays,witheachinnerarrayrepresentingaserver,witha
' server ' (string)attributethatistheIPaddresorhostnameofthememcachedserver,anda ' port ' (int)attributethatistheportnumberonwhichmemcachedisrunningontheserver.

AlloftheexistingmemcachedAPIfunctionsareimplementedexceptgetStats()andgetVersion(),whichareserver-specific.

<?php
classMemcachedAggregator{
var$connections;

publicfunction__construct($servers){
//Attempttoestablish/retrievepersistentconnectionstoallservers.
//Ifanyofthemfail,theyjustdon
' tgetputintoour list ofactive
// 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 (
分享到:
评论
isiqi
  • 浏览: 4175491 次
  • 性别: Icon_minigender_1
  • 来自: 济南
社区版块
存档分类
最新评论

你可能感兴趣的:(PHP,应用服务器,.net,软件测试,memcached)