swoole搭建web服务器及异步任务task

前提要先安装php的swoole扩展

共两个文件http.php与user.php,两个在同一个文件夹下

http.php代如下:

<?php

use server\Task;

class Http {

    const HOST = '0.0.0.0';

    const PORT = 9501;

    

    private $http = null;

    

    public function __construct() {

        $this->http = new Swoole\Http\Server(self::HOST, self::PORT);

        $this->http->set(self::config());

        $this->http->on("request", [$this, "onRequest"]);

        $this->http->on('Task', [$this, 'onTask']);

        $this->http->on('finish', [$this, 'onFinish']);

        $this->http->start();

    }

    

    private function config()

    {

        return [

            "enable_static_handler" => true,    //开启静态资源访问

            "document_root" => "/Users/johnson/WorkRoom/Project/live.csm.com/uniapp/",  //访问的根目录

            'worker_num' => 4,      //配置为cpu个数的1-4倍"

            'task_worker_num' => 4,

            //"open_http_protocol" => true,

            //"ssl_cert_file" => "",

            //"ssl_key_file"=>"",

        ];

    }

    

    public function onRequest($request, $response) {

        //使用 Chrome 浏览器访问服务器,会产生额外的一次请求,/favicon.ico,可以在代码中响应 404 错误

        if ($request->server['path_info'] == '/favicon.ico' || $request->server['request_uri'] == '/favicon.ico') {

            $response->end();

            return;

        }

        //

        $response->header('Content-Type', 'text/html; charset=utf-8');

        $reg_file = $request->server["request_uri"];

        

        //让其它php页面可以拿到$this->http

        $_SERVER['http'] = $this->http;

        //

        

        $file_path = __DIR__ . $reg_file;

        $res = '';

        if (file_exists($file_path))

        {

            ob_start();

            include $file_path;

            $res = ob_get_contents();

            ob_end_clean();

        }

        $response->end($res);

    }

    

    public function onTask($serv, $task_id, $reactor_id, $data) {

        require_once  __DIR__ . '/task.php';

        $obj = new Task();

        $method = $data['method'];

        $res = $obj->$method($data['data'], $serv);

        //sleep(5);

        return "task finish";

    }

    

    public function onFinish($serv, $task_id, $data)

    {

        echo "AsyncTask[{$task_id}] Finish: {$data}".PHP_EOL;

    }

}

new Http();

user.php代码如下

<?php

echo "hello,johnson".PHP_EOL;

$task_data = [

    'method' => 'sendSms',

    'data' => [

        'phone' => '13950909098',

        'code' => '1234'

    ]

];

$_SERVER['http']->task($task_data);

命令行里执行  php http.php  开启swoole的http服务

在浏览器里运行 http://localhost:9501/user.php  就可以看到输出的内容,切换到命令行也能看到异步任务输出的内容

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值