利用swoole_process和eventloop实现php异步编程

思路很简单:

开一个子进程处理异步事务,处理完之后,通过管道告诉父进程,并将返回数据写入管道

代码如下:

AsynHttpClient.php

url = $url;
        $this->callback = $callback;
        $this->run();
    }

    public function run()
    {
        $this->process = new swoole_process([$this, "callback"], true); 
        $this->process->start();
        swoole_event_add($this->process->pipe, function($pipe) {
            $content = $this->process->read();
            call_user_func($this->callback, $content);
            swoole_event_del($this->process->pipe);
        });
    }

    public function callback(swoole_process $process)
    {
        $ch = curl_init($this->url);

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        $content = curl_exec($ch);

        curl_close($ch);
        
        $process->write($content);
    }
}

index.php

require 'AsynHttpClient.php';

new AsynHttpClient("http://127.0.0.1:9000/api.php", function($data) {
   print_r($data);
});

echo 1;

api.php

 'ok',
  'data' => 'hello',
]);
php -S 127.0.0.1:9000

可以看到运行结果是1在前面, 证明是异步执行的.

其实通过php中的pcntl_fork和libevent也可以实现, 不需要借助swoole, 但是swoole提供的process确实很好用

https://www.iwantmoney.cn/art...

你可能感兴趣的:(swoole,php)