/etc/php/{version}/fpm/php.ini(如/etc/php/8.1/fpm/php.ini),启用OPcache并配置参数:zend_extension=opcache.so
opcache.enable=1
opcache.memory_consumption=128 # 缓存内存大小(MB)
opcache.interned_strings_buffer=8 # 内部字符串缓冲区大小
opcache.max_accelerated_files=4000 # 最大加速文件数
opcache.revalidate_freq=60 # 文件检查频率(秒)
重启PHP-FPM使配置生效:sudo systemctl restart php{version}-fpm。/etc/php/{version}/fpm/pool.d/www.conf,使用dynamic模式并设置合理进程数:pm = dynamic
pm.max_children = 50 # 最大子进程数(建议为内存的1/4,如8GB内存设为20)
pm.start_servers = 5 # 启动时的子进程数
pm.min_spare_servers = 5 # 最小空闲进程数
pm.max_spare_servers = 35 # 最大空闲进程数
重启PHP-FPM:sudo systemctl restart php{version}-fpm。location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/var/run/php/php{version}-fpm.sock;
}
测试配置并重启Nginx:sudo nginx -t && sudo systemctl restart nginx。sudo apt install redis-server php-redis
sudo systemctl enable --now redis-server
修改ThinkPHP配置文件config/cache.php,设置Redis为默认缓存驱动:return [
'default' => 'redis',
'stores' => [
'redis' => [
'type' => 'redis',
'host' => '127.0.0.1',
'port' => 6379,
'expire' => 3600, // 默认缓存过期时间(秒)
'prefix' => 'tp6:', // 缓存前缀
],
],
];
使用缓存示例:use think\facade\Cache;
Cache::set('access_token', 'value', 3600); // 设置缓存
$token = Cache::get('access_token'); // 获取缓存
Cache::rm('access_token'); // 删除缓存
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查询问题:$users = User::with('posts')->select(); // 预加载用户的文章
pconnect(持久连接)减少连接建立和关闭的开销。在config/database.php中配置:'connections' => [
'mysql' => [
'type' => 'mysql',
'hostname' => '127.0.0.1',
'database' => 'dbname',
'username' => 'username',
'password' => 'password',
'charset' => 'utf8mb4',
'prefix' => '',
'persistent' => true, // 开启持久连接
],
],
OPTIMIZE TABLE整理碎片,清理无用数据;优化查询语句(通过EXPLAIN分析执行计划)。foreach ($users as $user) {
$order = Order::where('user_id', $user->id)->find();
}
改为:$userIds = array_column($users, 'id');
$orders = Order::whereIn('user_id', $userIds)->select();
gzip on;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
gzip_comp_level 6;
gzip_min_length 1024;
重启Nginx使配置生效。async或defer属性异步加载JavaScript文件。config/log.php中设置'slow_query' => 1)。