在 Linux + ThinkPHP 环境下进行优化,通常可以从 服务器、PHP、ThinkPHP 框架、数据库、缓存、代码 几个层面来做。下面按实用优先级给你一份优化清单。
Nginx 示例:
location ~ \.php$ {
fastcgi_pass unix:/run/php/php8.1-fpm.sock;
include fastcgi_params;
}
sudo apt install php-opcache
php.ini 配置:
opcache.enable=1
opcache.memory_consumption=128
opcache.max_accelerated_files=10000
opcache.revalidate_freq=60
✅ 可提升 30%~50% 性能
www.conf:
pm = dynamic
pm.max_children = 50
pm.start_servers = 10
pm.min_spare_servers = 5
pm.max_spare_servers = 20
根据内存调整:
free -h
.env
APP_DEBUG = false
php think optimize:route
php think optimize:config
php think optimize:autoload
composer install --optimize-autoloader --no-dev
slow_query_log = 1
long_query_time = 1
ALTER TABLE user ADD INDEX idx_status (status);
field() 减少字段limit() 限制数量select() 全表User::where('status',1)->field('id,name')->limit(10)->select();
高并发场景:
.env
CACHE_TYPE=redis
REDIS_HOST=127.0.0.1
REDIS_PORT=6379
Cache::remember('user_list', 60, function () {
return User::select();
});
Nginx:
location ~* \.(js|css|png|jpg)$ {
expires 30d;
}
with() 预加载关联errorUser::with('profile')->select();
top / htopphp-fpm statusmysqltunerblackfirexhprof| 优化项 | 提升效果 |
|---|---|
| OPcache | ⭐⭐⭐⭐ |
| 路由/配置缓存 | ⭐⭐⭐ |
| Redis 缓存 | ⭐⭐⭐⭐ |
| 数据库索引 | ⭐⭐⭐⭐ |
| Swoole | ⭐⭐⭐⭐⭐ |
如果你愿意,可以告诉我:
我可以给你 针对性优化方案或配置文件示例。