Webman如何使用Swow事件驱动和协程?

开发 前端
Swow 是一个专注于并发 I/O 的跨平台协程引擎,它致力于使用最小 C 核心及多数 PHP 代码以支持 PHP 高性能网络编程,具有极佳的扩展性与强大的调试能力,最大化开发者的编程效率。

Swow 是什么?

Swow 是一个专注于并发 I/O 的跨平台协程引擎,它致力于使用最小 C 核心及多数 PHP 代码以支持 PHP 高性能网络编程,具有极佳的扩展性与强大的调试能力,最大化开发者的编程效率。

安装

安装workerman 5.0

composer require workerman/workerman v5.0.0-beta.7

安装日志

composer require workerman/workerman v5.0.0-beta.7
./composer.json has been updated
Running composer update workerman/workerman
Loading composer repositories with package information
Updating dependencies
Lock file operations: 0 installs, 1 update, 0 removals
  - Upgrading workerman/workerman (v5.0.0-beta.1 => v5.0.0-beta.7)
Writing lock file
Installing dependencies from lock file (including require-dev)
Package operations: 0 installs, 1 update, 0 removals
  - Downloading workerman/workerman (v5.0.0-beta.7)
  - Upgrading workerman/workerman (v5.0.0-beta.1 => v5.0.0-beta.7): Extracting archive
> support\Plugin::install
Generating autoload files
11 packages you are using are looking for funding.
Use the `composer fund` command to find out more!
No security vulnerability advisories found.

安装swow拓展

拉取源码

composer require swow/swow

安装日志

./composer.json has been updated
Running composer update swow/swow
Loading composer repositories with package information
Updating dependencies
Lock file operations: 5 installs, 0 updates, 0 removals
  - Locking composer/semver (3.4.2)
  - Locking psr/http-client (1.0.3)
  - Locking psr/http-factory (1.0.2)
  - Locking psr/http-message (2.0)
  - Locking swow/swow (v1.5.3)
Writing lock file
Installing dependencies from lock file (including require-dev)
Package operations: 5 installs, 0 updates, 0 removals
  - Installing psr/http-message (2.0): Extracting archive
  - Installing psr/http-factory (1.0.2): Extracting archive
  - Installing psr/http-client (1.0.3): Extracting archive
  - Installing composer/semver (3.4.2): Extracting archive
  - Installing swow/swow (v1.5.3): Extracting archive
> support\Plugin::install
> support\Plugin::install
> support\Plugin::install
> support\Plugin::install
> support\Plugin::install
1 package suggestions were added by new dependencies, use `composer suggest` to see details.
Generating autoload files
12 packages you are using are looking for funding.
Use the `composer fund` command to find out more!
No security vulnerability advisories found.
Using version ^1.5 for swow/swow

然后运行 vendor/bin 目录下的自动安装器 swow-builder 即可开始安装:

./vendor/bin/swow-builder

安装日志

# ./vendor/bin/swow-builder
> cd /var/www/webman2024/vendor/swow/swow/ext && \
phpize && \
./configure 
Configuring for:
PHP Api Version:         20230831
Zend Module Api No:      20230831
Zend Extension Api No:   420230831
...
Directive => Local Value => Master Value
swow.enable => On => On
swow.async_threads => 0 => 0
swow.async_file => On => On
swow.async_tty => On => On

👀 Do you want to install it right now? (Y/n): Y
> cd /var/www/webman2024/vendor/swow/swow/ext && \
make install
Installing shared extensions:     /usr/local/lib/php/extensions/no-debug-non-zts-20230831/
✅ Install done

🚀🚀🚀 All tasks have been completed 🚀🚀🚀

出现以上结果,恭喜你安装成功啦!!!

开启swow事件驱动

在webman框架中开启swow事件驱动特别简单,只有配置一下就可以了。

修改配置文件config/server.php服务配置文件

return [
    'listen'           => 'http://0.0.0.0:8787',
    'transport'        => 'tcp',
    'context'          => [],
    'name'             => 'webman',
    'count'            => cpu_count() * 10,
    'user'             => '',
    'group'            => '',
    'reusePort'        => false,
    'event_loop'       => \Workerman\Events\Swow::class,
    'stop_timeout'     => 2,
    'pid_file'         => runtime_path() . '/webman.pid',
    'status_file'      => runtime_path() . '/webman.status',
    'stdout_file'      => runtime_path() . '/logs/stdout.log',
    'log_file'         => runtime_path() . '/logs/workerman.log',
    'max_package_size' => 10 * 1024 * 1024
];

启动webman,查看事件驱动是否已经是swow事件驱动。使用以下命令启动

php -d extension=swow webman start

终端展示

/var/www/webman2024 # php -d extension=swow webman start
Workerman[webman] start in USER mode
-------------------------------------------------- WORKERMAN --------------------------------------------------
Workerman version:5.0.0-beta.7    PHP version:8.3.9     Event-loop:Workerman\Events\Swow
--------------------------------------------------- WORKERS ---------------------------------------------------
proto   user            worker                       listen                      processes    state            
tcp     root            webman                       http://0.0.0.0:8217         8             [OK]            
tcp     root            monitor                      none                        1             [OK]            
tcp     root            push_chart                   none                        1             [OK]            
tcp     root            plugin.webman.push.server    websocket://0.0.0.0:8788    1             [OK]            
---------------------------------------------------------------------------------------------------------------
Press Ctrl+C to stop. Start success.

查看运行状态php start.php status

图片图片

协程

协程,英文Coroutines,是一种比线程更加轻量级的存在。最重要的是,协程不是被操作系统内核所管理,而完全是由程序所控制(也就是在用户态执行)。

<?php
/**
 * @desc swow.php 描述信息
 * @author Tinywan(ShaoBo Wan)
 */
declare(strict_types=1);
use Exception;
use Swow\Coroutine;

$coroutine = Coroutine::run(static function (): void {
    while (true) {
        try {
            // output: int(999)
            var_dump(sleep(999));
        } catch (\Exception) {
            // skip
        }
    }
});
$coroutine->resume(); // resume the coroutine to cancel the sleep
$coroutine->throw(new Exception()); // throw exception to the coroutine
$coroutine->kill(); // kill the coroutine (just like SIGKILL)

debug模式

\Swow\Coroutine::run(static function (): void {
    (static function (): void {
        (static function (): void {
            var_dump(\Swow\Coroutine::getCurrent());
        })();
    })();
});

执行输出

/var/www/webman2024/app/controller/indexController.php:29:
class Swow\Coroutine#243 (5) {
  public $id =>
  int(13)
  public $state =>
  string(7) "running"
  public $switches =>
  int(0)
  public $elapsed =>
  string(3) "0ms"
  public $trace =>
  string(1252) "
#0 [internal function]: Swow\Coroutine->__debugInfo()
#1 /var/www/webman2024/app/controller/indexController.php(29): var_dump(Object(Swow\Coroutine))
#2 /var/www/webman2024/app/controller/indexController.php(30): app\controller\IndexController::app\controller\{closure}()
#3 /var/www/webman2024/app/controller/indexController.php(31): app\controller\IndexController::app\controller\{closure}()
#4 [internal function]: app\controller\IndexController::app\controller\{closure}()
#5 /var/www/webman2024/app/control"...
}
责任编辑:武晓燕 来源: 开源技术小栈
相关推荐

2025-01-26 00:00:15

PHP协程控制权

2023-08-08 08:00:00

架构Kafka

2023-12-13 09:56:13

​多进程多线程协程

2024-10-18 10:27:50

PHP框架webma

2018-06-05 15:41:22

进程线程协程

2023-06-21 08:00:00

微服务架构

2024-10-22 15:34:57

2023-12-17 14:24:46

计算机进程线程

2023-11-29 08:02:16

线程进程

2023-10-31 22:54:17

GoEventBus驱动编程

2024-08-27 12:49:20

2023-02-07 07:25:36

Spring事件驱动

2021-01-28 11:17:49

Python爬虫单线程

2022-07-21 13:36:39

API事件驱动Rest

2019-04-19 21:06:23

事件驱动架构VANTIQ

2015-05-29 13:59:53

2021-12-23 09:00:00

架构微服务数据

2021-01-31 11:47:08

C语言SetjmpLongjmp

2009-06-25 14:05:08

Ajax JSF

2023-07-12 08:30:52

服务架构事件驱动架构
点赞
收藏

51CTO技术栈公众号