1. 安装并配置OPcache(关键优化)
OPcache是PHP内置的字节码缓存扩展,可避免重复编译脚本,显著提升执行效率。在CentOS上,通过以下步骤启用并优化:
sudo yum install php-opcache(若使用PHP 7+,也可用dnf)。/etc/php.ini,添加/修改以下配置:[opcache]
zend_extension=opcache.so
opcache.enable=1
opcache.memory_consumption=128 # 根据服务器内存调整(如256MB内存可设为192)
opcache.interned_strings_buffer=8
opcache.max_accelerated_files=4000 # 建议设为脚本总数的1.5倍
opcache.revalidate_freq=60 # 生产环境设为60秒以上(减少文件检查开销)
opcache.fast_shutdown=1
sudo systemctl restart php-fpm。2. 优化PHP-FPM进程管理
PHP-FPM是PHP FastCGI进程管理器,合理配置可平衡性能与资源占用:
/etc/php-fpm.d/www.conf(或对应池配置文件),调整进程参数:pm = dynamic # 动态调整进程数(适合大多数场景)
pm.max_children = 50 # 最大子进程数 = (服务器可用内存 - 1GB) / 单个进程内存(如256MB进程约可设30-50)
pm.start_servers = 5 # 启动时的进程数
pm.min_spare_servers = 5 # 最小空闲进程数(避免频繁创建)
pm.max_spare_servers = 35 # 最大空闲进程数(避免资源浪费)
pm.max_requests = 500 # 每个子进程处理500个请求后重启(防止内存泄漏)
3. 调整PHP核心配置
优化php.ini中的关键参数,提升处理能力和稳定性:
memory_limit = 256M(根据应用需求调整,如大型应用可设为512M)。max_execution_time = 300(默认30秒,适合上传或复杂计算场景)。disable_functions = exec,passthru,shell_exec,system(生产环境禁用危险函数,防止恶意利用)。output_buffering = On(减少HTTP请求次数,提升响应速度)。realpath_cache_size = 4096K(加快文件路径解析,适合多文件应用)。4. 使用高效Web服务器并优化配置
选择高性能Web服务器(如Nginx),并与PHP-FPM正确集成:
sudo yum install nginx,启动并设为开机自启:sudo systemctl enable --now nginx。server {
listen 80;
server_name example.com;
root /var/www/html;
index index.php index.html;
location / {
try_files $uri $uri/ =404;
}
location ~ \.php$ {
include fastcgi_params;
fastcgi_pass unix:/run/php-fpm/www.sock; # 使用Unix socket(比TCP更快)
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
}
}
gzip on; gzip_types text/plain text/css application/json;)、静态文件缓存等。5. 引入缓存系统(减少数据库负载)
使用Redis或Memcached缓存频繁访问的数据(如数据库查询结果、会话),降低数据库压力:
sudo yum install redis,启动服务:sudo systemctl start redis。sudo pecl install redis,添加extension=redis.so到php.ini。$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
$cacheKey = 'user_data_1';
if ($redis->exists($cacheKey)) {
$userData = $redis->get($cacheKey);
} else {
$userData = $pdo->query("SELECT * FROM users WHERE id = 1")->fetch();
$redis->setex($cacheKey, 3600, serialize($userData)); // 缓存1小时
}
6. 代码级优化(减少资源消耗)
优化代码逻辑,降低内存和CPU占用:
unset($data)(如处理完大型数组后)。LIMIT和OFFSET分页查询,或用yield生成器逐行处理(避免一次性加载所有数据到内存)。$stmt = $pdo->prepare("SELECT * FROM table WHERE id = ?");(防止SQL注入,提升查询效率)。7. 升级PHP版本(获得性能提升)
CentOS默认仓库的PHP版本可能较旧,升级到最新稳定版(如PHP 8.3)可获得JIT编译、性能优化等特性:
sudo yum install https://rpms.remirepo.net/enterprise/remi-release-7.rpm(CentOS 7)或对应版本的Remi仓库。sudo yum-config-manager --enable remi-php83。sudo yum update php php-fpm php-opcache。8. 监控与持续优化
定期监控服务器资源(内存、CPU、磁盘)和PHP性能,识别瓶颈:
top、htop查看实时资源使用情况。vmstat 1监控系统级性能(如CPU、内存、IO)。php-fpm status(sudo systemctl status php-fpm)查看PHP-FPM进程状态。