OPcache是提升PHP执行效率的关键扩展,可缓存编译后的PHP脚本,避免重复解析。在php.ini中添加/修改以下配置:
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使配置生效:systemctl restart php-fpm。
根据服务器资源(内存、CPU核心数)优化PHP-FPM进程管理,避免进程过多或过少导致资源浪费。示例配置(/etc/php-fpm.d/www.conf):
pm = dynamic # 动态进程管理模式
pm.max_children = 50 # 最大子进程数(建议:内存MB/20,如1GB内存设为50)
pm.start_servers = 5 # 启动时的进程数
pm.min_spare_servers = 5 # 最小空闲进程数
pm.max_spare_servers = 35 # 最大空闲进程数
重启PHP-FPM:systemctl restart php-fpm。
调整内核参数提升网络和内存性能,编辑/etc/sysctl.conf:
net.ipv4.tcp_tw_reuse = 1 # 复用TIME-WAIT连接
net.ipv4.tcp_fin_timeout = 30 # TIME-WAIT超时时间(秒)
vm.swappiness = 10 # 减少内存交换(值越小越优先使用物理内存)
应用配置:sysctl -p。
WHERE、JOIN字段)、排序(ORDER BY)和分组(GROUP BY)字段创建索引,避免全表扫描。SELECT *:只查询需要的列,减少数据传输量。mysql.connector.pooling)复用数据库连接,减少连接建立/关闭的开销。slow_query_log=1),使用EXPLAIN分析执行计划,优化低效SQL(如缺少索引、全表扫描)。启用MySQL查询缓存(query_cache_type=1)或使用Redis/Memcached作为应用层缓存,缓存频繁访问的数据库查询结果(如商品分类、用户信息),减少数据库负载。
配置ThinkPHP的缓存机制,缓存配置、路由、页面等数据,减少重复计算和数据库查询。示例配置(config/cache.php):
return [
'default' => 'redis', // 使用Redis作为缓存驱动
'stores' => [
'redis' => [
'type' => 'redis',
'host' => '127.0.0.1',
'port' => 6379,
'password' => '',
'select' => 0,
'timeout' => 0,
'persistent' => false,
'prefix' => 'tp6:', // 缓存前缀
],
],
];
开启路由缓存(config/route.php):
'route_check_cache' => true, // 开启路由检查缓存
开启配置缓存(命令行):
php think optimize:config # 生成配置缓存文件
with(预加载)代替foreach中的find,解决N+1查询问题。示例:$users = User::with('posts')->select(); // 一次性获取用户及关联的文章
Db::name('user')->insertAll($dataList); // 批量插入
server {
listen 80;
server_name yourdomain.com;
root /www/wwwroot/yourproject/public;
location / {
try_files $uri $uri/ /index.php?s=$uri&$args; # ThinkPHP URL重写
}
location ~ \.php$ {
fastcgi_pass 127.0.0.1:9000; # PHP-FPM地址
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
# 开启GZIP压缩
gzip on;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
}
将静态资源(图片、CSS、JS、字体)上传至CDN(内容分发网络),利用CDN节点缓存资源,减少服务器带宽压力和响应时间。
使用Nginx或HAProxy实现负载均衡,将请求分发到多台服务器,提升系统并发处理能力。示例Nginx负载均衡配置:
upstream thinkphp_servers {
server 192.168.1.101:80;
server 192.168.1.102:80;
server 192.168.1.103:80;
}
server {
listen 80;
server_name yourdomain.com;
location / {
proxy_pass http://thinkphp_servers;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}
使用Prometheus+Grafana监控服务器(CPU、内存、磁盘、网络)和应用(QPS、响应时间、错误率)指标,及时发现性能瓶颈。
debug级别日志),减少日志写入开销。示例配置(config/log.php):return [
'default' => 'file',
'channels' => [
'file' => [
'type' => 'file',
'path' => LOG_PATH,
'level' => ['error'], // 仅记录错误日志
'apart_level'=> [],
'max_files' => 30, // 保留30天日志
],
],
];
runtime目录下的缓存文件(如runtime/cache、runtime/temp)。