在PHP使用MemCached

來源:互聯網
上載者:User

在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) }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.