sudo apt update && sudo apt upgrade,确保Debian系统及PHP、数据库等软件包为最新版本,修复安全漏洞并提升性能。fastcgi_pass指向PHP-FPM的socket)处理PHP请求,避免Apache的mod_php带来的资源消耗。/etc/php/{version}/fpm/pool.d/www.conf({version}为PHP版本,如8.2),根据服务器内存设置:
pm.max_children:最大子进程数(建议为(总内存 - 系统占用) / 单个PHP进程内存,如1GB内存可设为20-30);pm.start_servers:启动时的子进程数(设为pm.max_children的1/4-1/2);pm.min_spare_servers/pm.max_spare_servers:最小/最大空闲进程数(保持空闲进程以应对突发请求);pm.max_requests:单个进程处理的最大请求数(如3000,防止内存泄漏)。php.ini(如/etc/php/{version}/fpm/php.ini),添加以下配置:[opcache]
zend_extension=opcache.so
opcache.enable=1
opcache.memory_consumption=128 # OPcache缓存大小(MB,根据内存调整)
opcache.interned_strings_buffer=8
opcache.max_accelerated_files=10000 # 缓存文件数量
opcache.revalidate_freq=60 # 检查脚本更新的频率(秒)
opcache.validate_timestamps=0 # 生产环境关闭时间戳验证(提升性能)
重启PHP-FPM使配置生效:sudo systemctl restart php{version}-fpm。config/cache.php,优先使用Redis(高性能内存缓存)或Memcached:return [
'default' => 'redis', // 默认缓存驱动
'stores' => [
'redis' => [
'type' => 'redis',
'host' => '127.0.0.1',
'port' => 6379,
'password' => '', // 如有密码需填写
'select' => 0, // Redis数据库索引
'expire' => 3600, // 默认缓存过期时间(秒)
'prefix' => 'tp6:', // 缓存前缀(避免键冲突)
],
// 文件缓存(备用,适合小数据量)
'file' => [
'type' => 'file',
'path' => runtime_path() . 'cache',
],
],
];
php think optimize:route # 生成路由缓存
php think optimize:config # 生成配置缓存
注:生产环境需关闭调试模式(
config/app.php中debug => false),避免不必要的日志输出。
WHERE、JOIN、ORDER BY字段添加索引(如CREATE INDEX idx_username ON users(username)),避免全表扫描。SELECT *(只查询所需字段);with方法实现关联预加载(解决N+1查询问题,如User::with('posts')->select());cache方法缓存结果(如$data = cache('user_list', function() { return User::select(); }, 3600))。p:前缀创建持久连接(如$db = new \think\db\Connection(['type' => 'mysql', 'hostname' => 'p:127.0.0.1'], ...)),减少连接建立/关闭的开销。insertAll、updateAll)。Db类默认是单例)。gzip on; gzip_types text/css application/javascript;),减少传输体积。htop(查看CPU/内存使用率)、vmstat(查看系统负载)、mysqladmin status(查看数据库状态)等工具实时监控系统资源。/var/log/php{version}-fpm.log)、ThinkPHP日志(runtime/log),定位性能瓶颈(如慢查询、内存泄漏)。runtime目录下的缓存、日志、临时文件(如runtime/cache、runtime/log),释放磁盘空间。