學習路之PHP--webman協程學習
- 一、準備
- 二、配置
- 三、啟動
- 四、使用
協程是一種比線程更輕量級的用戶級并發機制,能夠在進程中實現多任務調度。它通過手動控制掛起和恢復來實現協程間的切換,避免了進程上下文切換的開銷
一、準備
PHP >= 8.1
Workerman >= 5.1.0 (composer require workerman/workerman ~v5.1)
webman-framework >= 2.1 (composer require workerman/webman-framework ~v2.1)
安裝了swoole或者swow擴展,或者安裝了composer require revolt/event-loop (Fiber)
協程默認是關閉的,需要單獨設置eventLoop開啟
二、配置
config\process.php 增加
'my-webman' => ['handler' => Http::class,'listen' => 'http://0.0.0.0:8686','count' => 1,'user' => '','group' => '','reusePort' => false,// 開啟協程需要設置為 Workerman\Events\Swoole::class 或者 Workerman\Events\Swow::class 或者 Workerman\Events\Fiber::class'eventLoop' => Workerman\Events\Swoole::class,'context' => [],'constructor' => ['requestClass' => Request::class,'logger' => Log::channel('default'),'appPath' => app_path(),'publicPath' => public_path()]],
三、啟動
php start.php start
四、使用
- app\controller\IndexController.php
class IndexController
{public function index(Request $request){Coroutine::create(function(){Timer::sleep(10);echo "hello coroutine\n";});return response('hello webman');}
結果:
http://47.112.111.11:8686/ 協程方式訪問接口:馬上輸出hello webman,10秒后在進程守護器日志里輸出hello coroutine
http://47.112.111.11:8787/ 非協程方式訪問:直接卡10秒,然后顯示hello webman,進程守護器日志里輸出hello coroutine
其他官方參考
https://www.workerman.net/doc/webman/coroutine/coroutine.html