php記憶體緩衝實現程式碼

來源:互聯網
上載者:User

1.Memcached緩衝。
memcached是高效能的分布式記憶體快取服務器,通過快取資料庫查詢結果,減少資料庫訪問次數,以提高動態Web應用的速度。memcached 使用了“Key=>Value”方式組織資料。可以允許不同主機上的多個使用者同時訪問這個緩衝系統,一般用於大型網站使用。memcached使用記憶體快取資料,所以它是易失的,當伺服器重啟,或者memcached進程中止,資料便會丟失,所以 memcached不能用來持久儲存資料。

過php_memcache的人都會覺得 PHP記憶體緩衝是一個很複雜的東西,其實不然。
memcached 是高效、快速的分布式記憶體對象緩衝系統,主要用於加速 WEB Live App程式。
這裡介紹memcached在WIN32下的配置及其使用。

一、PHP記憶體緩衝的配置(WIN32環境)

1、下載php_memcache.rar,請從附件下載。

     解壓壓縮包:php_memcache.rar

     php_memcache.rar壓縮包裡主包含的檔案有:

     /memcached-1.2.1-win32/memcached.exe
     /php_memcache/php_memcache.dll

2、開啟命令提示字元,指向到memcached.exe所在路徑,運行memcached.exe -d start。

3、將php_memcache.dll檔案拷貝到PHP的動態檔案庫的檔案夾下。

4、在php.ini檔案中加入一行extension=php_memcache.dll。

5、重新啟動Apache,然後查看一下phpinfo,如果有memcache,那麼就說明安裝成功!


例:

 代碼如下 複製代碼

<?php
//包含 memcached 類檔案
require_once('memcached-client.php');
 
//選項設定
$options = array(
 'servers' => array('www.hxsd.com:11211'),//memcached 服務的地址、連接埠
 'debug' => true,//是否開啟debug
 'compress_threshold' => 10240,//超過多少位元組的資料時進行壓縮
 'persistant' => false//是否使用持久串連
 );
 
//執行個體化memcached對象
$memcached = new memcached($options);
 
$sql = 'SELECT * FROM table1';
$key = md5($sql);
 
//如果在memcached中沒有快取資料,把快取資料寫入memcached
if(!($datas = $memcached->get($key)))
{
 $conn = mysql_connect('localhost', 'hxsd', '123456');
 mysql_select_db('hxsd');
 $result = mysql_query($sql);
 while($row = mysql_fetch_object($result))
 {
  $datas[] = $row;
 }
 //將資料庫中擷取到的結果集資料儲存到 memcached 中,以供下次訪問時使用。
 $memcached->add($key, $datas);
}
else
{
 //直接使用memcached中的快取資料$datas
}
?>

記憶體緩衝二

APC、EC、Zend加速器的比較

一、APC

APC,全稱是Alternative PHP Cache,官方翻譯叫”可選PHP緩衝”。

首頁是 http://pecl.php.net/package/apc

php協助手冊頁面: http://cn.php.net/apc


APC是個最佳化器,自安裝之日起,就默默地在後台為您的PHP應用服務了.您的所有PHP代碼會被緩衝起來. (針對php opcode)

另外,APC可提供一定的記憶體緩衝功能.但是這個功能並不是十分完美,有報告說如果頻繁使用APC緩衝的寫入功能,會導致不可預料的錯誤.如果想使用這個功能,可以看看apc_fetch,apc_store等幾個與apc緩衝相關的函數.

安裝:

 代碼如下 複製代碼

# pecl install APC

配置:(/etc/php.inc)

 代碼如下 複製代碼

extension=apc.so

[apc]

 代碼如下 複製代碼

apc.enabled = 1

apc.shm_segments = 1

apc.shm_size = 30

apc.optimization = 0

apc.ttl = 7200

apc.user_ttl = 7200

apc.num_files_hint = 1000

apc.mmap_file_mask = /tmp/apc.XXXXXX

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.