利用swoole_process和eventloop實現php非同步程式設計

church發表於2019-02-16

思路很簡單:

開一個子程式處理非同步事務,處理完之後,通過管道告訴父程式,並將返回資料寫入管道

程式碼如下:

AsynHttpClient.php

<?php 

class AsynHttpClient
{
    public $url;

    public $callback;

    private $process;

    public function __construct($url, $callback) 
    {
        $this->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

<?php 

echo json_encode([
  `state` => `ok`,
  `data` => `hello`,
]);
php -S 127.0.0.1:9000

可以看到執行結果是1在前面, 證明是非同步執行的.

其實通過php中的pcntl_fork和libevent也可以實現, 不需要藉助swoole, 但是swoole提供的process確實很好用

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

相關文章