利用swoole_process和eventloop實現php異步編程

思路很簡單:php

開一個子進程處理異步事務,處理完以後,經過管道告訴父進程,並將返回數據寫入管道shell

代碼以下:json

AsynHttpClient.phpapi

<?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.phpswoole

require 'AsynHttpClient.php';

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

echo 1;

api.phpcurl

<?php 

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

能夠看到運行結果是1在前面, 證實是異步執行的.異步

其實經過php中的pcntl_fork和libevent也能夠實現, 不須要藉助swoole, 可是swoole提供的process確實很好用ui

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

相關文章
相關標籤/搜索