在PHP中使用Memcached,有兩種方式,一種是安裝PHP的{
undefined
}">memcache擴充(實際上還有另外一個{
undefined
}">memcached擴充,是基於比較流行的libmemcached庫封裝的),該擴充是用c寫的,效率較高,需要在伺服器上安裝。另外一種則是直接使用用戶端的php-memcached-client類庫,但是這個我在網上找了半天也沒找到一個官方的網站。所以呢,還是裝個擴充吧。假設php安裝在/home/admin/php目錄:
wget http://pecl.php.net/get/memcache-2.2.5.tgzgzip -d memcache-2.2.5.tgztar xvf memcache-2.2.5.tarcd memcache-2.2.5/home/admin/php/bin/phpizeConfiguring for:PHP Api Version: 20041225Zend Module Api No: 20060613Zend Extension Api No: 220060519./configure --enable-memcache --with-php-config=/home/admin/php/bin/php-config --with-zlib-dirInstalling shared extensions: /home/admin/php/lib/php/extensions/no-debug-non-zts-20060613/
注意到最後一行返回的資訊,將下面兩行添加到/home/admin/php/lib/php.ini
extension_dir = "/home/admin/php/lib/php/extensions/no-debug-non-zts-20060613/"extension=memcache.so
然後重啟web伺服器即可。如果安裝成功,則通過phpinfo()可以獲得該擴充的相關資訊:
| memcache support |
enabled |
| Active persistent connections |
0 |
| Version |
2.2.5 |
| Revision |
$Revision: 1.111 $ |
| Directive |
Local Value |
Master Value |
| memcache.allow_failover |
1 |
1 |
| memcache.chunk_size |
8192 |
8192 |
| memcache.default_port |
11211 |
11211 |
| memcache.default_timeout_ms |
1000 |
1000 |
| memcache.hash_function |
crc32 |
crc32 |
| memcache.hash_strategy |
standard |
standard |
| memcache.max_failover_attempts |
20 |
20 |
以上參數都可以在php.ini中進行設定。下面是一段官方網站的php測試代碼:
<?php$memcache = new Memcache;$memcache->connect('127.0.0.1', 11211) or die ("Could not connect");$version = $memcache->getVersion();echo "Server's version: ".$version."/n";$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)/n";$get_result = $memcache->get('key');echo "Data from the cache:/n";var_dump($get_result);?>
運行後輸出如下:
Server's version: 1.2.6Store data in the cache (data will expire in 10 seconds)Data from the cache: object(stdClass)#3 (2){ ["str_attr"]=> string(4) "test" ["int_attr"]=> int(123) }