Debian服务器上ThinkPHP性能调优指南
Debian系统需通过PHP-FPM管理PHP进程,编辑/etc/php/8.x/fpm/pool.d/www.conf(根据PHP版本调整路径),优化以下参数:
pm.max_children:根据服务器内存计算(如1GB内存可设为20-30),避免进程过多导致内存耗尽;pm.start_servers:设置为pm.max_children的1/4(如20则设为5),保证空闲进程快速响应;pm.min_spare_servers/pm.max_spare_servers:分别设置为pm.max_children的1/8和1/4(如3和7),动态调整进程数量。sudo systemctl restart php8.x-fpm。OPcache缓存PHP脚本编译结果,显著减少重复编译时间。编辑/etc/php/8.x/fpm/php.ini,启用并配置:
opcache.enable=1
opcache.memory_consumption=128 # 缓存大小(MB),根据内存调整
opcache.max_accelerated_files=10000 # 缓存文件数量
opcache.validate_timestamps=0 # 生产环境关闭,避免频繁检查文件修改
重启PHP-FPM使配置生效。
id、status、created_at)添加索引,避免全表扫描;EXPLAIN分析慢查询,优化SELECT *为指定字段,避免不必要的数据加载;User::with('profile')->select()),将多个查询合并为1个。php-redis扩展),在config/cache.php中设置默认驱动为Redis:'default' => env('CACHE_DRIVER', 'redis'),
'stores' => [
'redis' => [
'type' => 'redis',
'host' => env('REDIS_HOST', '127.0.0.1'),
'port' => env('REDIS_PORT', 6379),
'password' => env('REDIS_PASSWORD', ''),
'select' => 0,
],
],
User::insertAll($data))替代循环单条插入,减少数据库连接次数。cache()函数缓存频繁访问的数据(如商品分类、配置信息),设置合理过期时间(如3600秒):$cacheKey = 'category_list';
$categories = cache($cacheKey) ?: Category::select();
cache($cacheKey, $categories, 3600);
php think optimize:route(生成路由缓存)和php think optimize:autoload(生成自动加载缓存),减少路由解析和类加载时间。location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ {
expires 30d;
add_header Cache-Control "public, no-transform";
}
server {
listen 80;
server_name yourdomain.com;
root /path/to/thinkphp/public;
index index.php;
location / {
try_files $uri $uri/ /index.php?$query_string;
}
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/run/php/php8.x-fpm.sock;
}
}
gzip on;
gzip_types text/css application/javascript text/plain application/xml;
修改后重启Nginx:sudo systemctl restart nginx。
禁用Apache的mod_autoindex(自动索引)、mod_include(SSI)等不常用模块,减少资源消耗。
foreach中调用find()),改用批量查询;User::get(1)->articles),仅在需要时加载关联数据,减少初始加载时间;APP_DEBUG=false),关闭调试信息和SQL日志,减少不必要的输出。top、htop监控CPU、内存使用情况,定位瓶颈(如内存不足需升级配置);runtime/log目录)和缓存(runtime/cache目录),释放磁盘空间。调整Debian内核参数(/etc/sysctl.conf),优化网络性能:
net.ipv4.tcp_max_syn_backlog = 4096
net.ipv4.tcp_tw_reuse = 1
net.core.somaxconn = 1024
运行sudo sysctl -p使配置生效。
Debian默认仓库的PHP版本可能较旧,建议通过deb.sury.org仓库安装最新稳定版(如PHP 8.2),新版本包含性能改进和优化。
安装依赖时启用优化(composer install --no-dev --optimize-autoloader),减少自动加载器的开销;生产环境移除开发依赖(composer remove --dev package-name)。
以上优化措施需根据ThinkPHP项目的实际负载(如并发量、数据量)和业务场景调整,建议先在测试环境验证效果,再部署到生产环境。