学习路之PHP--webman协程学习

学习路之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开启

学习路之PHP--webman协程学习_第1张图片

二、配置

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
学习路之PHP--webman协程学习_第2张图片

四、使用

  1. 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

你可能感兴趣的:(webman,php,学习,php,android)