Detailed explanation of swoole’s task case of asynchronous delivery

Time:2020-4-24

An example of this paper describes the implementation of asynchronous delivery task in swoole. To share with you for your reference, as follows:

[usage scenario]

Swoolle’s task module can be used to do some asynchronous slow tasks and time-consuming scenarios. For example, webim sends broadcast and email. After these tasks are left to the task process, the worker process can continue to process new data requests. After the task is completed, the worker process will be notified asynchronously to tell it that the task has been completed. In addition, tasks can also be used to realize PHP database connection pool, asynchronous queue, etc.

[instructions for use]

The number of task processes must be set: task worker num

Deliver an asynchronous task to the task pool: server – > task

Event callback functions ontask and onfinish2 must be registered.

[example]

Take creating a websocket service asynchronous delivery task as an example:

ws_server.php:

<?php

class Ws {
  public $ws = null;
  public function __construct() {
    $this->ws = new swoole_websocket_server("0.0.0.0", 9501);
    $this->ws->set([
        'worker \ num' = > 2, // number of worker processes
        'task \ worker \ num' = > 2, // number of task processes
      ]);
    $this->ws->on("open", [$this, 'onOpen']);
    $this->ws->on("message", [$this, 'onMessage']);
    $this->ws->on("task", [$this, 'onTask']);
    $this->ws->on("finish", [$this, 'onFinish']);
    $this->ws->on("close", [$this, 'onClose']);
    $this->ws->start();
  }

  //Establish connection callback
  public function onOpen($ws, $request) {
    Echo "{$request - > FD} establishes the connection";
  }

  //Accept message callback
  public function onMessage($ws, $frame) {
    //The worker process delivers tasks asynchronously to the task & worker process
    $data = [
      'fd' => $frame->fd,
    ];
    $ws->task($data);

    //Server return
    Echo "server sends message: 666";
  }

  //Complete asynchronous task callback
  public function onTask($serv, $task_id, $worker_id, $data) {
    var_dump($data);

    //Simulate slow task
    sleep(5);

    //Return string to worker process -- > trigger onfinish
    return "success";
  }

  //Complete task delivery callback
  public function onFinish($serv, $task_id, $data) {
    //Task? Worker process sends task processing results to worker process
    Echo "complete task {$task {ID} delivery processing result: {$data}";
  }

  //Close connection callback
  public function onClose($ws, $fd) {
    Echo "{$FD} closed the connection";
  }
}

$obj = new Ws();

Front end page JS listening:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>WebSocket</title>
</head>
<body>
</body>
<script type="text/javascript">
var websocket = new WebSocket('ws://127.0.0.1:9501'); 

websocket.onopen = function (evt) { onOpen(evt) }; 
websocket.onclose = function (evt) { onClose(evt) }; 
websocket.onmessage = function (evt) { onMessage(evt) }; 
websocket.onerror = function (evt) { onError(evt) }; 
 
function onOpen(evt) {
  console.log("Connected to WebSocket server."); 
  
  //*Send message to websocket server
  websocket.send('666');
} 
function onClose(evt) { 
  console.log("Disconnected"); 
}
function onMessage(evt) { 
  console.log('Retrieved data from server: ' + evt.data); 
} 
function onError(evt) { 
  console.log('Error occured: ' + evt.data); 
}
</script>
</html>

Open websocket service:


php ws_server.php

After refreshing the page twice, the websocket server listens to the result:

(the server will return the message to the client first, and then perform the delivery task.)

For more information about PHP, you can see the following topics: PHP extended development tutorial, PHP object-oriented programming introduction tutorial, PHP mathematical operation skills summary, PHP array operation skills Collection, PHP data structure and calculation tutorial, PHP programming algorithm summary, PHP regular expression Usage Summary and PHP common See summary of database operation skills

I hope that this article will be helpful for PHP programming.