在一個標(biāo)準(zhǔn)的 PHP 環(huán)境中,每次訪問PHP腳本時,腳本都會被編譯然后執(zhí)行。 一次又一次地花費時間編譯相同的腳本對于大型站點會造成性能問題。
解決方案是采用一個 opcode 緩存。 opcode 緩存是一個能夠記下每個腳本經(jīng)過編譯的版本,這樣服務(wù)器就不需要浪費時間一次又一次地編譯了。 通常這些 opcode 緩存系統(tǒng)也能智能地檢測到一個腳本是否發(fā)生改變,因此當(dāng)你升級 PHP 源碼時,并不需要手動清空緩存。
PHP 5.5 內(nèi)建了一個緩存 OPcache。PHP 5.2 - 5.4 下可以作為PECL擴展安裝。
此外還有幾個PHP opcode 緩存值得關(guān)注 eaccelerator, xcache,以及APC。 APC 是 PHP 項目官方支持的,最為活躍,也最容易安裝。 它也提供一個可選的類 memcached 的持久化鍵-值對存儲,因此你應(yīng)使用它。
在 Ubuntu 12.04 上你可以通過在終端中執(zhí)行以下命令來安裝 APC:
user@localhost: sudo apt-get install php-apc
除此之外,不需要進一步的配置。
APC 也提供了對于你的腳本透明的類似于 memcached 的功能。 與使用 memcached 相比一個大的優(yōu)勢是 APC 是集成到 PHP 核心的,因此你不需要在服務(wù)器上維護另一個運行的部件, 并且 PHP 開發(fā)者在 APC 上的工作很活躍。 但從另一方面來說,APC 并不是一個分布式緩存,如果你需要這個特性,你就必須使用 memcached 了。
<?php
// Store some values in the APC cache. We can optionally pass a time-to-live,
// but in this example the values will live forever until they're garbage-collected by APC.
apc_store('username-1532', 'Frodo Baggins');
apc_store('username-958', 'Aragorn');
apc_store('username-6389', 'Gandalf');
// After storing these values, any PHP script can access them, no matter when it's run!
$value = apc_fetch('username-958', $success);
if($success === true)
print($value); // Aragorn
$value = apc_fetch('username-1', $success); // $success will be set to boolean false, because this key doesn't exist.
if($success !== true) // Note the !==, this checks for true boolean false, not "falsey" values like 0 or empty string.
print('Key not found');
apc_delete('username-958'); // This key will no longer be available.
?>
如果你使用的不是 PHP-FPM(例如你在使用 mod_php 或 mod_fastcgi), 那么每個 PHP 進程都會有自己獨有的 APC 實例,包括鍵-值存儲。 若你不注意,這可能會在你的應(yīng)用代碼中造成同步問題。