请问各位大佬v5版本中的协程,是怎么使用的?

happy321

请问各位大佬v5版本中的协程,是怎么使用的?

哪些情况建议使用,需要注意哪些?

185 1 2
1个回答

用法和swoole swow中文档一样。

例如swow中使用连接池代码类似

<?php

use Workerman\Connection\TcpConnection;
use Workerman\Events\Swow;
use Workerman\Protocols\Http\Request;
use Swow\Channel;
use Workerman\Worker;

require_once __DIR__ . '/vendor/autoload.php';

$worker = new Worker('http://0.0.0.0:2345');
$worker->eventLoop = Swow::class;
$worker->count = 1;
$pool = null;
$worker->onWorkerStart = function () {
    global $pool;
    $pool = new Pool('mysql:host=127.0.0.1;dbname=your_database', 'root', 'your_password', 10);
};
$worker->onMessage = function (TcpConnection $connection, Request $request) {
    global $pool;
    // 连接池获取pdo对象
    $pdo = $pool->get();
    $stmt = $pdo->query('SELECT 1');
    $result = $stmt->fetch(PDO::FETCH_ASSOC);
    // 连接池回收pdo对象
    $pool->put($pdo);
    $connection->send(json_encode($result));
};

class Pool
{
    protected Channel $channel;

    public function __construct($dsn, $username, $password, $size)
    {
        $this->channel = new Channel($size);
        for ($i = 0; $i < $size; $i++) {
            $this->channel->push(new PDO($dsn, $username, $password,[
                PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
            ]));
        }
    }

    public function get(): PDO
    {
        return $this->channel->pop();
    }

    public function put(PDO $pdo)
    {
        return $this->channel->push($pdo);
    }
}

Worker::runAll();

swoole 连接池用法

<?php

use Workerman\Connection\TcpConnection;
use Workerman\Events\Swoole;
use Workerman\Protocols\Http\Request;
use Workerman\Worker;
use Swoole\Database\PDOConfig;
use Swoole\Database\PDOPool;

require_once __DIR__ . '/vendor/autoload.php';

$worker = new Worker('http://0.0.0.0:2346');
$worker->eventLoop = Swoole::class;
$worker->count = 2;
$pool = null;
$worker->onWorkerStart = function () {
    global $pool;
    $config = (new PDOConfig())
        ->withDriver('mysql')
        ->withHost('127.0.0.1')
        ->withPort(3306)
        ->withDbName('your_database')
        ->withUsername('root')
        ->withPassword('your_password');
    $pool = new PDOPool($config, 10);
};
$worker->onMessage = function (TcpConnection $connection, Request $request) {
    global $pool;
    // 连接池获取pdo对象
    $pdo = $pool->get();
    $stmt = $pdo->query('SELECT 1');
    $result = $stmt->fetch(PDO::FETCH_ASSOC);
    // 连接池回收pdo对象
    $pool->put($pdo);
    $connection->send(json_encode($result));
};

Worker::runAll();
  • 暂无评论
×
🔝