請問各位大佬v5版本中的協(xié)程,是怎么使用的?
哪些情況建議使用,需要注意哪些?
用法和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();