缓存 PHP opcode
使用 APC
在一个标准的 PHP 环境中,每次访问PHP脚本时,脚本都会被编译然后执行。 一次又一次地花费时间编译相同的脚本对于大型站点会造成性能问题。
解决方案是采用一个 opcode 缓存。 opcode 缓存是一个能够记下每个脚本经过编译的版本,这样服务器就不需要浪费时间一次又一次地编译了。 通常这些 opcode 缓存系统也能智能地检测到一个脚本是否发生改变,因此当你升级 PHP 源码时,并不需要手动清空缓存。
PHP 5.5 内建了一个缓存 OPcache。PHP 5.2 - 5.4 下可以作为PECL扩展安装。
此外还有几个PHP opcode 缓存值得关注 eaccelerator, xcache,以及APC。 APC 是 PHP 项目官方支持的,最为活跃,也最容易安装。 它也提供一个可选的类 memcached 的持久化键-值对存储,因此你应使用它。
安装 APC
在 Ubuntu 12.04 上你可以通过在终端中执行以下命令来安装 APC:
user@localhost: sudo apt-get install php-apc
除此之外,不需要进一步的配置。
将 APC 作为一个持久化键-值存储系统来使用
APC 也提供了对于你的脚本透明的类似于 memcached 的功能。 与使用 memcached 相比一个大的优势是 APC 是集成到 PHP 核心的,因此你不需要在服务器上维护另一个运行的部件, 并且 PHP 开发者在 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 实例,包括键-值存储。 若你不注意,这可能会在你的应用代码中造成同步问题。
{$ activeFileHint $}