Skip to content

协程使用 ​

Kuiper Swoole 模块提供了完整的协程支持,包括协程检测、上下文管理和延迟执行等功能。

协程概述 ​

协程 (Coroutine) 是轻量级的用户态线程,可以在单个进程中创建数万个协程。相比传统多进程或多线程模式,协程具有以下优势:

  • 低内存占用: 每个协程仅占用几 KB 内存
  • 快速切换: 协程切换在用户态完成,无需内核介入
  • 高并发: 单进程可同时处理数万个并发请求
  • 同步代码: 使用同步代码风格编写异步逻辑

Coroutine::isEnabled() ​

检测当前是否运行在协程环境中。

使用示例 ​

php
<?php

declare(strict_types=1);

use kuiper\swoole\coroutine\Coroutine;

// 在 Swoole 协程环境中
\Swoole\Coroutine\run(function () {
    echo "协程环境: " . (Coroutine::isEnabled() ? '是' : '否') . "\n";
    // 输出: 协程环境: 是
});

// 在传统 PHP 环境中
echo "协程环境: " . (Coroutine::isEnabled() ? '是' : '否') . "\n";
// 输出: 协程环境: 否

在库代码中使用 ​

php
<?php

declare(strict_types=1);

use kuiper\swoole\coroutine\Coroutine;

class DatabaseClient
{
    public function query(string $sql): array
    {
        if (Coroutine::isEnabled()) {
            // 使用协程客户端
            return $this->queryInCoroutine($sql);
        } else {
            // 使用同步客户端
            return $this->querySync($sql);
        }
    }

    private function queryInCoroutine(string $sql): array
    {
        // 协程查询逻辑
        return [];
    }

    private function querySync(string $sql): array
    {
        // 同步查询逻辑
        return [];
    }
}

Coroutine::getCoroutineId() ​

获取当前协程的唯一 ID。如果不在协程环境中,返回 0。

使用示例 ​

php
<?php

declare(strict_types=1);

use kuiper\swoole\coroutine\Coroutine;

\Swoole\Coroutine\run(function () {
    echo "主协程 ID: " . Coroutine::getCoroutineId() . "\n";
    // 输出: 主协程 ID: 1

    // 创建子协程
    go(function () {
        echo "子协程 ID: " . Coroutine::getCoroutineId() . "\n";
        // 输出: 子协程 ID: 2
    });
});

日志追踪 ​

php
<?php

declare(strict_types=1);

use kuiper\swoole\coroutine\Coroutine;
use Psr\Log\LoggerInterface;

class RequestHandler
{
    public function __construct(
        private readonly LoggerInterface $logger
    ) {
    }

    public function handle(string $path): void
    {
        $coroutineId = Coroutine::getCoroutineId();
        $this->logger->info("处理请求", [
            'path' => $path,
            'coroutine_id' => $coroutineId,
        ]);

        // 处理请求逻辑
    }
}

在非协程环境中 ​

php
<?php

declare(strict_types=1);

use kuiper\swoole\coroutine\Coroutine;

// 在传统 PHP-FPM 环境中
$coroutineId = Coroutine::getCoroutineId();
echo "协程 ID: " . $coroutineId . "\n";
// 输出: 协程 ID: 0

// 可以用进程 ID 替代
$processId = getmypid();
echo "进程 ID: " . $processId . "\n";

Coroutine::getContext() ​

获取当前协程的上下文对象。上下文是一个 ArrayObject,用于在协程内共享数据。

基本使用 ​

php
<?php

declare(strict_types=1);

use kuiper\swoole\coroutine\Coroutine;

\Swoole\Coroutine\run(function () {
    // 获取当前协程上下文
    $context = Coroutine::getContext();

    // 存储数据
    $context['userId'] = 123;
    $context['requestId'] = uniqid();

    // 在同一协程中读取数据
    echo "User ID: " . $context['userId'] . "\n";
    echo "Request ID: " . $context['requestId'] . "\n";

    // 在嵌套协程中访问
    go(function () {
        $parentContext = Coroutine::getContext();
        echo "嵌套协程中访问: " . $parentContext['userId'] . "\n";
    });
});

请求上下文管理 ​

php
<?php

declare(strict_types=1);

use kuiper\swoole\coroutine\Coroutine;

class RequestContext
{
    public static function set(string $key, mixed $value): void
    {
        $context = Coroutine::getContext();
        $context[$key] = $value;
    }

    public static function get(string $key, mixed $default = null): mixed
    {
        $context = Coroutine::getContext();
        return $context[$key] ?? $default;
    }

    public static function has(string $key): bool
    {
        $context = Coroutine::getContext();
        return isset($context[$key]);
    }

    public static function remove(string $key): void
    {
        $context = Coroutine::getContext();
        unset($context[$key]);
    }
}

// 使用示例
\Swoole\Coroutine\run(function () {
    RequestContext::set('userId', 123);
    RequestContext::set('sessionId', 'abc123');

    echo "User ID: " . RequestContext::get('userId') . "\n";
    echo "Has sessionId: " . (RequestContext::has('sessionId') ? 'yes' : 'no') . "\n";

    RequestContext::remove('sessionId');
    echo "Has sessionId: " . (RequestContext::has('sessionId') ? 'yes' : 'no') . "\n";
});

获取其他协程的上下文 ​

php
<?php

declare(strict_types=1);

use kuiper\swoole\coroutine\Coroutine;

\Swoole\Coroutine\run(function () {
    $parentId = Coroutine::getCoroutineId();
    Coroutine::getContext()['parentData'] = 'from parent';

    go(function () use ($parentId) {
        $childId = Coroutine::getCoroutineId();
        Coroutine::getContext()['childData'] = 'from child';

        // 获取父协程的上下文
        $parentContext = Coroutine::getContext($parentId);
        echo "父协程数据: " . $parentContext['parentData'] . "\n";
    });

    \Swoole\Coroutine::sleep(0.001);
});

Coroutine::defer() ​

注册延迟执行的回调函数,当协程结束时自动执行。类似 Go 语言的 defer。

资源清理 ​

php
<?php

declare(strict_types=1);

use kuiper\swoole\coroutine\Coroutine;

function processFile(string $path): void
{
    $file = fopen($path, 'r');

    // 注册清理函数
    Coroutine::defer(function () use ($file) {
        echo "关闭文件\n";
        fclose($file);
    });

    // 处理文件
    while (($line = fgets($file)) !== false) {
        echo $line;
    }

    // 函数结束时自动关闭文件
}

多个 defer 的执行顺序 ​

php
<?php

declare(strict_types=1);

use kuiper\swoole\coroutine\Coroutine;

\Swoole\Coroutine\run(function () {
    echo "开始\n";

    Coroutine::defer(function () {
        echo "清理 3\n";
    });

    Coroutine::defer(function () {
        echo "清理 2\n";
    });

    Coroutine::defer(function () {
        echo "清理 1\n";
    });

    echo "结束\n";
});

// 输出顺序:
// 开始
// 结束
// 清理 1
// 清理 2
// 清理 3

数据库事务管理 ​

php
<?php

declare(strict_types=1);

use kuiper\swoole\coroutine\Coroutine;

class TransactionManager
{
    public function begin(PDO $db): void
    {
        $db->beginTransaction();

        Coroutine::defer(function () use ($db) {
            if ($db->inTransaction()) {
                $db->rollBack();
                echo "事务已回滚\n";
            }
        });
    }

    public function commit(PDO $db): void
    {
        if ($db->inTransaction()) {
            $db->commit();
            echo "事务已提交\n";
        }
    }
}

// 使用示例
$db = new PDO('mysql:host=localhost;dbname=test', 'user', 'password');
$manager = new TransactionManager();

$manager->begin($db);
try {
    // 执行数据库操作
    $db->exec("INSERT INTO users (name) VALUES ('John')");

    // 提交事务
    $manager->commit($db);
} catch (Exception $e) {
    echo "错误: " . $e->getMessage() . "\n";
    // defer 会自动回滚事务
}

Coroutine::clearContext() ​

清除当前协程的上下文(仅在非协程环境中有效)。

php
<?php

declare(strict_types=1);

use kuiper\swoole\coroutine\Coroutine;

// 在传统 PHP 环境中
$context = Coroutine::getContext();
$context['data'] = 'some value';

// 清除上下文
Coroutine::clearContext();

// 获取新的上下文
$newContext = Coroutine::getContext();
echo isset($newContext['data']) ? 'exists' : 'not exists';
// 输出: not exists

Channel (协程通道) ​

Channel 是协程间通信的机制,类似于 Go 语言的 channel。

基本使用 ​

php
<?php

declare(strict_types=1);

use kuiper\swoole\coroutine\Channel;

\Swoole\Coroutine\run(function () {
    $channel = new Channel(2);  // 容量为 2

    // 协程 1: 生产者
    go(function () use ($channel) {
        echo "生产: 1\n";
        $channel->push(1);

        echo "生产: 2\n";
        $channel->push(2);
    });

    // 协程 2: 消费者
    go(function () use ($channel) {
        \Swoole\Coroutine::sleep(0.001);
        echo "消费: " . $channel->pop() . "\n";
        echo "消费: " . $channel->pop() . "\n";
    });
});

超时操作 ​

php
<?php

declare(strict_types=1);

use kuiper\swoole\coroutine\Channel;

\Swoole\Coroutine\run(function () {
    $channel = new Channel(1);

    // 带超时的 push
    $success = $channel->push('data', 1.0);
    if ($success) {
        echo "推送成功\n";
    } else {
        echo "推送超时\n";
    }

    // 带超时的 pop
    $data = $channel->pop(1.0);
    if ($data !== false) {
        echo "获取数据: " . $data . "\n";
    } else {
        echo "获取超时\n";
    }
});

并发原语 ​

Lock (锁) ​

php
<?php

declare(strict_types=1);

use Swoole\Coroutine\Lock;
use kuiper\swoole\coroutine\Coroutine;

\Swoole\Coroutine\run(function () {
    $lock = new Lock();

    // 协程 1
    go(function () use ($lock) {
        $lock->lock();
        echo "协程 1 获得锁\n";
        \Swoole\Coroutine::sleep(0.1);
        echo "协程 1 释放锁\n";
        $lock->unlock();
    });

    // 协程 2
    go(function () use ($lock) {
        \Swoole\Coroutine::sleep(0.01);
        echo "协程 2 等待锁\n";
        $lock->lock();
        echo "协程 2 获得锁\n";
        $lock->unlock();
    });
});

计数器 (Counter) ​

Swoole\Coroutine\Counter 在 Swoole 5.x 之后已移除,Kuiper 提供了基于 \Swoole\Atomic 的跨协程计数器:kuiper\swoole\concurrency\ConcurrencyFactory::createCounter()。 它只提供 add() / get() / set(),不具备阻塞等待能力——等待协程完成请用 Channel。

php
<?php

declare(strict_types=1);

use kuiper\swoole\concurrency\ConcurrencyFactory;
use Swoole\Coroutine;
use Swoole\Coroutine\Channel;

Coroutine\run(function () {
    // 跨协程共享的计数器(Swoole 环境基于 \Swoole\Atomic,无扩展时退化为普通实现)
    $counter = ConcurrencyFactory::createCounter(0);
    // 用 Channel 等待 3 个协程完成
    $done = new Channel(3);

    for ($i = 1; $i <= 3; $i++) {
        go(function () use ($i, $counter, $done) {
            echo "协程 {$i} 开始\n";
            Coroutine::sleep(0.1);
            $counter->add();
            echo "协程 {$i} 完成\n";
            $done->push(true);
        });
    }

    // 等待 3 个协程依次完成
    for ($i = 0; $i < 3; $i++) {
        $done->pop(1.0);
    }
    echo "所有协程已完成,计数 = ", $counter->get(), "\n";
});

协程注意事项 ​

1. 避免阻塞操作 ​

php
// ❌ 错误: 在协程中使用阻塞函数
\Swoole\Coroutine\run(function () {
    sleep(10);  // 阻塞整个进程
    file_get_contents('http://example.com');  // 阻塞 I/O
});

// ✅ 正确: 使用协程友好的函数
\Swoole\Coroutine\run(function () {
    \Swoole\Coroutine::sleep(10);  // 协程睡眠
    $client = new \Swoole\Coroutine\Http\Client('example.com', 80);
    $client->get('/');  // 协程 HTTP 客户端
});

2. 内存管理 ​

php
// ❌ 错误: 在协程间共享大对象
$largeObject = new LargeObject();

for ($i = 0; $i < 1000; $i++) {
    go(function () use ($largeObject) {
        // 所有协程共享同一个大对象
        process($largeObject);
    });
}

// ✅ 正确: 每个协程创建自己的对象
for ($i = 0; $i < 1000; $i++) {
    go(function () {
        $object = new LargeObject();  // 每个协程独立的对象
        process($object);
    });
}

3. 异常处理 ​

php
// ❌ 错误: 协程中的异常不会被自动捕获
go(function () {
    throw new Exception('协程异常');
});
// 异常会被 Swoole 捕获并记录日志

// ✅ 正确: 在协程中捕获异常
go(function () {
    try {
        // 可能抛出异常的代码
        riskyOperation();
    } catch (Exception $e) {
        echo "捕获异常: " . $e->getMessage() . "\n";
    }
});

完整示例 ​

并发 HTTP 请求 ​

php
<?php

declare(strict_types=1);

use kuiper\swoole\coroutine\Coroutine;
use Swoole\Coroutine\Http\Client;

class ConcurrentHttpClient
{
    /**
     * 并发执行多个 HTTP 请求
     *
     * @param array<array{url: string, method?: string, data?: array<string, mixed>}> $requests
     * @return array<string, mixed>
     */
    public function concurrentRequest(array $requests): array
    {
        if (!Coroutine::isEnabled()) {
            throw new \RuntimeException('必须在协程环境中使用');
        }

        $results = [];
        $channel = new \Swoole\Coroutine\Channel(count($requests));

        foreach ($requests as $key => $request) {
            go(function () use ($request, $key, $channel) {
                $url = parse_url($request['url']);
                $client = new Client($url['host'], 80);

                try {
                    if ($request['method'] ?? 'GET' === 'POST') {
                        $client->post($url['path'], $request['data'] ?? []);
                    } else {
                        $client->get($url['path']);
                    }

                    $channel->push([
                        'key' => $key,
                        'success' => $client->statusCode === 200,
                        'body' => $client->body,
                        'statusCode' => $client->statusCode,
                    ]);
                } catch (\Exception $e) {
                    $channel->push([
                        'key' => $key,
                        'success' => false,
                        'error' => $e->getMessage(),
                    ]);
                }
            });
        }

        // 收集结果
        for ($i = 0; $i < count($requests); $i++) {
            $result = $channel->pop();
            $results[$result['key']] = $result;
        }

        return $results;
    }
}

// 使用示例
\Swoole\Coroutine\run(function () {
    $client = new ConcurrentHttpClient();

    $requests = [
        'user1' => ['url' => 'http://api.example.com/users/1'],
        'user2' => ['url' => 'http://api.example.com/users/2'],
        'user3' => ['url' => 'http://api.example.com/users/3'],
    ];

    $results = $client->concurrentRequest($requests);

    foreach ($results as $key => $result) {
        if ($result['success']) {
            echo "{$key}: 成功\n";
        } else {
            echo "{$key}: 失败 - " . ($result['error'] ?? '未知错误') . "\n";
        }
    }
});

性能优势 ​

协程 vs 传统多进程 ​

text
测试场景: 10000 个 HTTP 请求

传统多进程模式:
- 创建 100 个进程
- 每个进程处理 100 个请求
- 总耗时: ~50 秒
- 内存占用: ~500 MB

协程模式:
- 单进程
- 创建 10000 个协程
- 总耗时: ~5 秒
- 内存占用: ~50 MB

性能提升: 10 倍
内存节省: 90%

更多资源 ​

基于 MIT 许可发布