Swoole---Http服务+Task异步任务

服务端



use think\Container;

class Http{
    CONST HOST = "0.0.0.0";
    CONST PORT = 8811;

    public $http = null;

    public function __construct()
    {
        $this->http = new swoole_http_server(self::HOST,self::PORT);

        $this->http->set([
            'enable_static_handler' => true,//开启静态页面访问
            'worker_num' => 4,
            'task_worker_num' => 4,
            'document_root' => "/usr/local/var/www/swoole_mooc/thinkphp/public/static",
        ]);

        $this->http->on("workerstart",[$this,'onWorkerStart']);
        $this->http->on("request",[$this,'onRequest']);
        $this->http->on("task", [$this,'onTask']);
        $this->http->on("finish", [$this,'onFinish']);//finish 操作是可选的,也可以不返回任何结果
        $this->http->on("close", [$this,'onClose']);
        $this->http->start();
    }

    public function onWorkerStart($server ,$worker_id){
        define('APP_PATH', __DIR__ . '/../application/');
        //加载框架里面的文件
        //require __DIR__ . '/../thinkphp/base.php';//拆分start.php里面的加载和启动
        require __DIR__ . '/../thinkphp/start.php';//拆分start.php里面的加载和启动
    }

    public function onRequest($request , $response)
    {
        $_SERVER = [];
        if (isset($request->server)){
            foreach ($request->server as $k => $v){
                $_SERVER[strtoupper($k)] = $v;
            }
        }
        if (isset($request->header)){
            foreach ($request->header as $k => $v){
                $_SERVER[strtoupper($k)] = $v;
            }
        }
        $_GET = [];
        if (isset($request->get)){
            foreach ($request->get as $k => $v){
                $_GET[$k] = $v;
            }
        }
        $_POST = [];
        if (isset($request->post)){
            foreach ($request->post as $k => $v){
                $_POST[$k] = $v;
            }
        }

        $_POST['http_server'] = $this->http;将对象传入
        ob_start();
        // 执行应用并响应
        try{
            Container::get('app', [APP_PATH])
                ->run()
                ->send();
        }catch (\Exception $e){
            //todo
        }
        $res = ob_get_contents();
        ob_end_clean();
        $response->end($res);//必须是字符串
    }

    /*
     * task任务
     * */
    public function onTask($serv, $taskId, $workerId, $data)
    {
        $obj = new app\common\lib\task\Task;
        $method = $data['method'];//这里使用了工厂模式
        $flag = $obj->$method($data['data']);

        return $flag;
    }
    //finish方法
    public function onFinish($serv, $taskId , $data){
        echo "taskId:{$taskId}\n";
        echo "finish-data-success:{$data}\n";//这里的data不是task方法里的参数data,是task方法返回的值传给finish方法
    }

    /*
     * 监听关闭事件
     * */
    public function onClose($http , $fd)
    {
        echo "client_id:{$fd}\n";
    }
}
new Http();

客户端

public function index()
    {
        $phoneNumber = request()->get('phone_num',0,'intval');
        if ($phoneNumber){
            $redis = new \Swoole\Coroutine\Redis();
            $redis->connect(config('redis.host'),config('redis.port'));
            $redis->set(Redis::smsKey($phoneNumber),'1234',config('redis.out_time'));
			//调用http里面的task任务
            $taskData = [
                'method' => 'sendSms',
                'data' => [
                    'phone' => $phoneNumber,
                    'code' => '1234',
                ]
            ];
            $_POST['http_server']->task($taskData);
            return Util::show(config('code.success'),'success');
        }
        return Util::show(config('code.errot'),'发送失败');
    }

Task任务类



namespace app\common\lib\task;

/**
 * Class Task
 * task异步任务类
 * @package app\common\lib\task
 */
class Task {
    //模拟发送验证码
    public function sendSms($data)
    {
        //print_r($data);
        //发送验证码,处理业务逻辑
        sleep(10);
        return ['status' => 'success'];
    }

}```
终端
```bash
 ✘  php http.php
taskId:0//这里10s后成功添加异步任务  
finish-data-success:on task finish
client_id:2
client_id:1

页面返回值
Swoole---Http服务+Task异步任务_第1张图片
这里是做了一个登陆发送验证码的异步任务,也可以加上redis或者登陆时候的设置cookie等操作。

你可能感兴趣的:(swoole)