OPCache是PHP官方推出的字节码缓存扩展,可避免重复解析、编译脚本,显著提升执行速度。
安装与配置步骤:
sudo yum install php-opcache(CentOS默认仓库已包含该扩展);php.ini文件(路径通常为/etc/php.ini),添加/修改以下参数:[opcache]
zend_extension=opcache.so ; 启用扩展
opcache.enable=1 ; 开启OPCache
opcache.memory_consumption=128 ; 分配给OPCache的内存大小(MB,根据服务器内存调整,建议64-256MB)
opcache.max_accelerated_files=4000 ; 可缓存的脚本文件数量(需覆盖项目所有PHP文件)
opcache.validate_timestamps=1 ; 生产环境设为0(禁用文件时间戳检查,提升性能),开发环境设为1(自动更新缓存)
opcache.revalidate_freq=60 ; 文件更新检查间隔(秒,生产环境可设为300以上)
opcache.fast_shutdown=1 ; 快速关闭机制,减少内存释放时间
sudo systemctl restart php-fpm。新版本PHP通常包含性能改进、bug 修复及新特性(如PHP 7+的JIT编译、PHP 8+的性能优化)。
升级步骤:
php -v;sudo yum install epel-release
sudo yum install https://rpms.remirepo.net/enterprise/remi-release-7.rpm # CentOS 7
sudo yum install https://rpms.remirepo.net/enterprise/remi-release-8.rpm # CentOS 8
sudo yum-config-manager --enable remi-php82
sudo yum update php php-*;sudo systemctl restart nginx php-fpm。PHP-FPM(FastCGI进程管理器)负责管理PHP进程,合理的配置可提升并发处理能力。
关键参数调整(编辑/etc/php-fpm.d/www.conf):
pm.max_children:最大子进程数,根据服务器内存计算(公式:可用内存(MB)/单个PHP进程内存(MB),如1GB内存、每个进程100MB,则设为10);pm.start_servers:启动时的子进程数(建议设为pm.max_children的1/4~1/2);pm.min_spare_servers:最小空闲进程数(避免频繁创建进程);pm.max_spare_servers:最大空闲进程数(避免占用过多内存)。pm.max_children = 10
pm.start_servers = 4
pm.min_spare_servers = 2
pm.max_spare_servers = 6
pm = dynamic(动态调整进程数,适合大多数场景);sudo systemctl restart php-fpm。频繁的数据库查询是PHP脚本的性能瓶颈之一,使用Memcached或Redis缓存热点数据可显著提升速度。
以Redis为例:
sudo yum install redis;sudo systemctl start redis;sudo yum install php-pecl-redis;$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
$cacheKey = 'user_list';
if ($data = $redis->get($cacheKey)) {
// 从缓存读取数据
$userList = json_decode($data, true);
} else {
// 从数据库查询数据
$userList = $db->query("SELECT * FROM users")->fetchAll();
// 存入缓存(有效期3600秒)
$redis->set($cacheKey, json_encode($userList), 3600);
}
代码层面的优化可直接减少资源消耗,提升执行效率:
require_once/include_once:这些语句会检查文件是否已包含,增加开销,若确定文件未重复包含,可使用require/include;int、string),减少PHP内部类型检查的开销。选择高性能Web服务器并调整配置,可减少HTTP请求处理时间:
gzip on; gzip_types text/plain text/css application/json application/javascript;);fastcgi_buffers 16 16k; fastcgi_buffer_size 32k;(优化PHP-FPM通信缓冲区);server {
listen 80;
server_name example.com;
root /var/www/html;
index index.php index.html;
location / {
try_files $uri $uri/ =404;
}
location ~ \.php$ {
fastcgi_pass unix:/var/run/php-fpm/php-fpm.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
}
sudo systemctl restart nginx。数据库查询慢会直接影响PHP脚本执行速度,需针对性优化:
SELECT *(只查询所需字段),使用EXPLAIN分析查询执行计划(识别全表扫描、索引缺失等问题);query_cache_type=1)或InnoDB缓冲池(innodb_buffer_pool_size,建议设为服务器内存的50%~70%);OPTIMIZE TABLE)、清理无用数据(如过期日志)。通过监控工具定位性能瓶颈,持续调整优化策略:
top(查看CPU/内存使用率)、htop(交互式资源监控)、vmstat(虚拟内存统计)、iostat(磁盘I/O统计);