安裝服務(wù)端
memcache是項(xiàng)目名,而在服務(wù)端的駐留進(jìn)程叫memcached(linux的守護(hù)進(jìn)程一般都是在后面加個(gè)d)。在OSX下使用brew可以快速安裝memcache:
$ sudo brew install memcached
memcache的依賴:openssl和libevent會(huì)自動(dòng)下載并安裝。
安裝完成后,使用如下命令啟動(dòng):
$ sudo memcached -m 32 -p 11211 -d
安裝php擴(kuò)展
使用php操作memcache前,需要安裝php的擴(kuò)展,php的擴(kuò)展有兩個(gè)可以選擇memcache和memcached,這里就安裝比較經(jīng)典的前者。從這里選擇一個(gè)版本下載源碼壓縮包,解壓,進(jìn)入到源碼目錄后執(zhí)行:
$ sudo phpize
phpize是幫助用來在已編譯好的php外,編譯php擴(kuò)展用的腳本,用來生成configure、make等文件。有時(shí)執(zhí)行這個(gè)命令會(huì)報(bào)錯(cuò):
Cannot find autoconf. Please check your autoconf installation and the$PHP_AUTOCONF environment variable. Then, rerun this script.
缺少依賴,那就安裝咯,還是使用brew:
$ sudo brew install autoconf
phpize完成后,依次實(shí)行如下命令實(shí)現(xiàn)編譯和安裝:
$ sudo ./configure$ sudo make$ sudo make install
編譯好的memcache.so一般被安裝到如下目錄:
Installing shared extensions: /usr/lib/php/extensions/no-debug-non-zts-xxxxxx/
這樣就可以在php.ini中配置這個(gè)擴(kuò)展了:
extension=/usr/lib/php/extensions/no-debug-non-zts-xxxxxx/memcache.so
打開phpinfo()頁面,查看memcache是否已經(jīng)加載成功:
設(shè)置yii
這樣其實(shí)已經(jīng)可以在php中直接使用memcache了,這里就不累述了,如果在yii中使用,則需要添加一個(gè)組件:
'components'=>array( 'cache'=>array( 'class'=>'CMemCache', 'servers'=>array( array( 'host'=>'127.0.0.1', 'port'=>11211 ) ), ),...
關(guān)于更多的yii配置請參閱其文檔。最后,在yii中使用memcache:
Yii::app()->cache->set('key1','value1');Yii::app()->cache->get('key1'); memcached使用示例
將純粹使用數(shù)據(jù)庫查詢的代碼加上memcached支持是很簡單的,假設(shè)這是原來的代碼:
function get_foo (int userid) { result = db_select("SELECT * FROM users WHERE userid = ?", userid); return result;} 加上memcached的緩存機(jī)制后:
function get_foo (int userid) { result = memcached_fetch("userrow:" + userid); if (!result) { result = db_select("SELECT * FROM users WHERE userid = ?", userid); memcached_add("userrow:" + userid, result); } return result;} 上述的程序會(huì)先到memcached檢查是否有userrow:userid的數(shù)據(jù),如果有則直接傳回結(jié)果,如果不存在時(shí)再去數(shù)據(jù)庫查詢,并將結(jié)果放到memcached內(nèi)。
在memcached內(nèi)已經(jīng)有緩存信息時(shí)將數(shù)據(jù)庫的數(shù)據(jù)更新后,上述的程序會(huì)抓到舊的數(shù)據(jù),這是屬于Cache coherency的問題。其中一種解決的方法是在更新數(shù)據(jù)庫時(shí),同時(shí)更新memcached內(nèi)的信息:
function update_foo(int userid, string dbUpdateString) { result = db_execute(dbUpdateString); if (result) { data = createUserDataFromDBString(dbUpdateString); memcached_set("userrow:"+userid, data); }} 

















