/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 # 內存緩存大?。∕B,根據服務器內存調整)
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
)、日志文件、臨時文件,釋放磁盤空間。