Skip to content
全部文档

并发

简介

有时你需要执行若干互不依赖的慢任务。在许多情况下,并发执行这些任务能显著提升性能。Laravel 的 Concurrency facade 提供了简洁、方便的 API,用于并发执行闭包。

工作原理

Laravel 通过将给定闭包序列化,并派发到一个隐藏的 Artisan CLI 命令来实现并发;该命令会反序列化闭包,并在其独立的 PHP 进程中调用。闭包执行完毕后,结果值会再序列化回父进程。

Concurrency facade 支持三种驱动:process(默认)、forksync

与默认的 process 驱动相比,fork 驱动性能更好,但只能在 PHP 的 CLI 环境中使用,因为 PHP 在 Web 请求期间不支持 fork。使用 fork 驱动之前,需要安装 spatie/fork 包:

shell
composer require spatie/fork

sync 驱动主要用于测试:当你希望禁用所有并发,并在父进程中按顺序执行给定闭包时。

运行并发任务

要运行并发任务,可调用 Concurrency facade 的 run 方法。run 方法接受一个闭包数组,这些闭包会在子 PHP 进程中同时执行:

php
use Illuminate\Support\Facades\Concurrency;
use Illuminate\Support\Facades\DB;

[$userCount, $orderCount] = Concurrency::run([
    fn () => DB::table('users')->count(),
    fn () => DB::table('orders')->count(),
]);

要使用特定驱动,可使用 driver 方法:

php
$results = Concurrency::driver('fork')->run(...);

或者,若要更改默认并发驱动,应通过 config:publish Artisan 命令发布 concurrency 配置文件,并更新其中的 default 选项:

shell
php artisan config:publish concurrency

命名结果

若希望按名称而非位置访问并发任务结果,可提供关联数组形式的闭包。每个结果会以与对应闭包相同的键返回:

php
use Illuminate\Support\Facades\Concurrency;
use Illuminate\Support\Facades\DB;

$results = Concurrency::run([
    'users' => fn () => DB::table('users')->count(),
    'orders' => fn () => DB::table('orders')->count(),
]);

$userCount = $results['users'];
$orderCount = $results['orders'];

任务超时

使用 process 驱动(默认)时,可向 run 方法提供超时时间,以指定并发任务在被终止前允许运行的最长秒数:

php
use Illuminate\Support\Facades\Concurrency;
use Illuminate\Support\Facades\DB;

[$userCount, $orderCount] = Concurrency::run([
    fn () => DB::table('users')->count(),
    fn () => DB::table('orders')->count(),
], timeout: 30);

若希望用更具表现力的方式定义超时,也可提供 CarbonInterval 实例:

php
use Illuminate\Support\Facades\Concurrency;

use function Illuminate\Support\seconds;

Concurrency::run([...], timeout: seconds(30));

延迟并发任务

若希望并发执行一组闭包,但不关心这些闭包的返回结果,可考虑使用 defer 方法。调用 defer 时,给定闭包不会立即执行;相反,Laravel 会在 HTTP 响应发送给用户之后再并发执行这些闭包:

php
use App\Services\Metrics;
use Illuminate\Support\Facades\Concurrency;

Concurrency::defer([
    fn () => Metrics::report('users'),
    fn () => Metrics::report('orders'),
]);