/etc/sysctl.conf:net.ipv4.tcp_fastopen = 3 # 启用TCP Fast Open减少握手延迟
vm.swappiness = 10 # 降低内存交换倾向(值越低越少用swap)
执行sysctl -p使配置生效。/etc/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 # 文件修改检查频率(秒)
opcache.validate_timestamps=1 # 生产环境设为0(禁用实时检查)
重启PHP-FPM使配置生效。SELECT *,只查询所需字段;EXPLAIN分析慢查询,优化执行计划;WHERE DATE(create_time) = '2025-10-01')。connection_pool功能)。SET GLOBAL slow_query_log = 'ON';
SET GLOBAL long_query_time = 1; # 记录执行时间超过1秒的查询
SET GLOBAL slow_query_log_file = '/var/log/mysql/slow.log';
/etc/nginx/conf.d/your_domain.conf):server {
listen 80;
server_name your_domain.com;
root /var/www/html/thinkphp/public;
index index.php;
location / {
try_files $uri $uri/ /index.php?s=$uri&$args; # ThinkPHP URL重写
}
location ~ \.php$ {
fastcgi_pass unix:/run/php-fpm/www.sock; # 与PHP-FPM通信
fastcgi_index index.php;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
}
# 开启GZIP压缩减少传输体积
gzip on;
gzip_types text/plain text/css application/json application/javascript;
gzip_comp_level 6;
}
测试配置并重启Nginx:nginx -t && systemctl restart nginx。/etc/php-fpm.d/www.conf(CentOS默认路径),设置动态进程管理模式:pm = dynamic # 动态调整进程数
pm.max_children = 50 # 最大子进程数(根据服务器内存计算:如1GB内存约设20-30)
pm.start_servers = 5 # 启动时的进程数
pm.min_spare_servers = 5 # 最小空闲进程数
pm.max_spare_servers = 10 # 最大空闲进程数
pm.max_requests = 500 # 每个子进程处理的最大请求数(防止内存泄漏)
重启PHP-FPM:systemctl restart php-fpm。// 配置缓存(config/cache.php)
return [
'default' => 'redis',
'stores' => [
'redis' => [
'type' => 'redis',
'host' => '127.0.0.1',
'port' => 6379,
'password' => '',
'select' => 0,
'timeout' => 0,
],
],
];
// 使用缓存(控制器中)
$data = cache('key_name');
if (!$data) {
$data = Db::table('table')->select();
cache('key_name', $data, 3600); // 缓存1小时
}
return cache('page_key')缓存整个页面,减少控制器执行。with(预加载)代替foreach中的单独查询,解决N+1问题:// 低效:循环中查询
$users = User::all();
foreach ($users as $user) {
$posts = $user->posts()->select(); // 每次循环都查询数据库
}
// 高效:预加载
$users = User::with('posts')->select(); // 一次查询获取所有用户及关联文章
insertAll、updateAll代替循环中的单条插入/更新,减少数据库交互次数。gzip部分)。top、htop查看CPU/内存使用,vmstat监控系统整体性能,php-fpm status查看PHP-FPM进程状态。/var/log/php-fpm/error.log)、ThinkPHP日志(runtime/log)及MySQL慢查询日志,定位性能瓶颈。runtime/cache)、日志文件、临时文件,释放磁盘空间。