解决方案是采用一个 opcode 缓存。
opcode 缓存是一个能够记下每个脚本经过编译的版本,这样服务器就不需要浪费时间一次又一次地编译了。
通常这些 opcode 缓存系统也能智能地检测到一个脚本是否发生改变,因此当你升级 PHP 源码时,并不需要手动清空缓存。
此外还有几个PHP opcode 缓存值得关注 , xcache,以及。
APC 是 PHP 项目官方支持的,最为活跃,也最容易安装。
它也提供一个可选的类 memcached 的持久化键-值对存储,因此你应使用它。
安装 APC
除此之外,不需要进一步的配置。
将 APC 作为一个持久化键-值存储系统来使用
示例
- <?php
- // Store some values in the APC cache. We can optionally pass a time-to-live,
- 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.
- ?>
陷阱
- 如果你使用的不是(例如你在使用mod_php或),
那么每个PHP进程都会有自己独有的APC实例,包括键-值存储。
若你不注意,这可能会在你的应用代码中造成同步问题。