Asynchronous message queuing API based on swoole

Posted by strangermaster on Mon, 27 Apr 2020 16:35:09 +0200

Explain

1. If you need to perform time-consuming operations in the Server program, such as a chat Server sending broadcast, and a Web Server sending mail. If these functions are executed directly, the current process will be blocked, resulting in slow response of the Server.

Swoole provides the function of asynchronous task processing, which can deliver an asynchronous task to the TaskWorker process pool for execution without affecting the processing speed of the current request. (official website description)

1. Server code

Execute server listening port 9501. By setting the parameter "daemonize", the daemons maintain the TaskWorker process pool in the system. Our client delivers the message to the server, and the server asynchronously puts the data request into the process pool queue to run, which greatly shortens the response time.
<?php
/**
 * Created by PhpStorm
 * User: pl
 * Date: 2020/4/26
 * Time: 10:29
 */


class TaskServers
{
    private $server;

    public function __construct()
    {

        $this->server = new Swoole\Server('127.0.0.1',9501);

        $this->server->set([
            'task_worker_num' => 3,     //The number of open processes is generally 1-4 times the number of cup cores
            'daemonize'       => 1,     //The program has been executed by the Daemons
            'max_request'     => 10000,  //Maximum tasks of worker process
            'dispatch_mode' => 2,        //Set to scramble mode
            'task_ipc_mode'   => 3,     //Set to message queuing mode
        ]);
        $this->server->on('Receive',array($this,'onReceive'));
        $this->server->on('Task',array($this,'onTask'));
        $this->server->on('Finish',array($this,'onFinish'));
        $this->server->start();
    }

    /**
     * @param swoole_server $server
     * @param $fd
     * @param $form_id
     * @param $data
     *  Start delivering asynchronous tasks
     */
    public function onReceive(swoole_server $server , $fd , $form_id , $data)
    {
        $this->server->task($data);
    }

    /**
     * @param swoole_server $server
     * @param $fd
     * @param $from_id
     * @param $data
     *  Perform asynchronous tasks
     */
    public function onTask( $server , $fd , $from_id , $data)
    {
        $data = json_decode($data,true);
        try {
            $log_txt =  date('Y-m-d H:i:s')."Start task".PHP_EOL ;
            $this->log($log_txt);
            return  $this->request_curl($data['url'],$data['data'],'post');
        }catch (\Exception $exception){
            $log_txt =  date('Y-m-d H:i:s')."Failed to execute task error".PHP_EOL ;
            $this->log($log_txt);
        }
    }

    public function onFinish( $server , $task_id, $data)
    {
        $log_txt =  date('Y-m-d H:i:s')."$data".PHP_EOL ;
        $this->log($log_txt);
    }
   public function request_curl($url = '', $request_data = '', $request_type = 'get', $headers = [], $is_ssl = false)
    {
            $ch = curl_init (); //curl initialization
            if( $request_type == 'get' && !empty( $request_data) )
            {
                $num = 0;
                foreach ( $request_data as $key => $value )
                {
                    if($num == 0)
                    {
                        $url .= '?' . $key.'='.$value;
                    }
                    else{
                        $url .= '&'. $key . '=' . $value;
                      }
                    $num ++;
                }
                $num = 0;
            }
            //Distinguish get from post
            curl_setopt ( $ch, CURLOPT_URL, $url ); //URL address
            curl_setopt ( $ch, CURLOPT_HEADER, 0 ); //Header information is not output
            //If the result is returned successfully, nothing will be output automatically
            curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );  
            //The post type implements this result
            if( $request_type == 'post')
            {
               //Set to POST mode
                curl_setopt ( $ch, CURLOPT_POST, 1 ); 
                 //POST data
                curl_setopt ( $ch, CURLOPT_POSTFIELDS, $request_data );  
                //Enforce when post data is greater than 1024
                curl_setopt ( $ch, CURLOPT_HTTPHEADER, array("Expect:")); 
            }
            //Determine whether to bypass the certificate
            if( $is_ssl )
            {
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);//Bypass ssl authentication
                curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
            }
            if(!empty($headers))  curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
            $result = curl_exec ( $ch ); //implement
            if ( $result == FALSE) return false;
            curl_close ( $ch ); //close resource
        return $result;
    }

    public function log($log_txt)
    {
        $log ='log/'.date('Y_m_d').'log';
        if(!file_exists($log)) {
            touch($log);
            chown($log,0777);
        }
        $file_log = fopen($log,"a");
        fputs($file_log,$log_txt);
        fclose($file_log);
    }
}
$task = new TaskServers();

  

2. Client code

<?php
/**
 * Created by PhpStorm
 * User: pl
 * Date: 2020/4/26
 * Time: 11:54
 */
class ClientRequest
{
    private $client;
    private $params; //Request parameters

    public function __construct($params)
    {
        $this->client = new swoole_client(SWOOLE_SOCK_TCP | SWOOLE_KEEP);
        $this->params = $params;
    }

    public function connect()
    {
        if (!$this->client->connect('127.0.0.1', 9501, 1)) {
            return json_encode([
                'code' => 500,
                'err_msg' => 'Failed to link asynchronous client'
            ]);
        }
        /**
         * Note request format
         * $params['url'] Interface address
         * $params['type']Interface request mode
         * $params['data']parameter
         */
        $params = $this->params;
        $array['url'] = $params['url'];
        unset($params['url']);
        $array['data'] = $params;
        $this->client->send(json_encode($array, JSON_UNESCAPED_UNICODE));
    }
}
if (!empty($_GET)) {
    $params = $_GET;
}
if (!empty($_POST)) {
    $params = $_POST;
}
$client = new ClientRequest($params);
$client->connect();

  

Start to execute the server-side program, php TaskServer.php we call another time-consuming interface in the form of an interface. Compare the response speed.

 

 

 

 

 

For more information, please visit:

Tencent T3-T4 standard boutique PHP architect tutorial directory, as long as you read it to ensure a higher salary (continuous update)

Topics: PHP PhpStorm Web Server curl