1. 启用Laravel Octane加速
Octane是Laravel的高性能服务器解决方案,通过Swoole、FrankenPHP等引擎替代传统PHP-FPM,显著提升请求处理速度。
composer require laravel/octanephp artisan octane:install --server=frankenphpphp artisan octane:startfastcgi_pass http://127.0.0.1:8000;),替代直接连接PHP-FPM。2. 优化PHP配置
php.ini(如/etc/php/8.2/fpm/php.ini),添加:[opcache]
zend_extension=opcache.so
opcache.enable=1
opcache.memory_consumption=512
opcache.interned_strings_buffer=64
opcache.max_accelerated_files=10000
opcache.revalidate_freq=60
opcache.fast_shutdown=1
/etc/php/8.2/fpm/pool.d/www.conf,设置动态进程池参数(根据服务器内存调整):pm = dynamic
pm.max_children = 50 # 最大子进程数(建议为内存的1/4,每进程约100MB)
pm.start_servers = 10 # 启动时的子进程数
pm.min_spare_servers = 5 # 最小空闲进程数
pm.max_spare_servers = 20 # 最大空闲进程数
request_terminate_timeout = 300 # 请求超时时间(秒)
3. 配置高效Web服务器(Nginx)
/etc/nginx/sites-available/your-site中的参数,提升并发处理能力:server {
listen 80;
server_name your-domain.com;
root /var/www/laravel/public;
index index.php;
# 静态文件缓存
location ~* \.(jpg|jpeg|png|gif|css|js|ico)$ {
expires 30d;
add_header Cache-Control "public, no-transform";
}
# PHP处理
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/run/php/php8.2-fpm.sock;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_read_timeout 300;
}
# 隐藏敏感文件
location ~ /\.ht {
deny all;
}
}
gzip on; gzip_types text/plain text/css application/json application/javascript;,减少传输体积。4. 使用Redis加速缓存
Redis作为内存数据库,比文件缓存更高效,适合缓存频繁访问的数据(如配置、路由、会话)。
sudo apt install redis-server php-redis(PHP扩展).env文件:CACHE_DRIVER=redis
SESSION_DRIVER=redis
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
Cache::remember缓存数据库查询结果(如热门文章):$popularPosts = Cache::remember('popular_posts', 3600, function () {
return Post::where('views', '>', 1000)->orderBy('views', 'desc')->take(10)->get();
});
5. 优化数据库查询
$books = Book::with('author')->get(); // 一次性加载书籍及作者信息
email、created_at)添加索引:Schema::table('users', function (Blueprint $table) {
$table->index(['email', 'created_at']);
});
$users = User::paginate(20); // 每页20条
6. 异步处理耗时任务(队列)
将邮件发送、文件处理等耗时任务放入队列,避免阻塞Web请求。
.env文件:QUEUE_CONNECTION=redisphp artisan make:job ProcessPodcast(生成app/Jobs/ProcessPodcast.php)dispatch方法:ProcessPodcast::dispatch($podcast)->onQueue('default');
php artisan queue:work --queue=default --tries=3(--tries指定重试次数)7. 缓存框架配置与路由
php artisan config:cache
php artisan route:cache
php artisan view:cache
注意:开发环境中禁用缓存(
APP_DEBUG=true),避免修改不生效。
8. 监控与性能分析
composer require laravel/telescope
php artisan telescope:install
php artisan migrate
composer require barryvdh/laravel-debugbar --dev
htop、vmstat等工具监控CPU、内存、磁盘使用情况,及时扩容。