Home Backend Development PHP Tutorial How does php use SwooleTaskWorker to implement asynchronous operation Mysql (code)

How does php use SwooleTaskWorker to implement asynchronous operation Mysql (code)

Oct 17, 2018 pm 04:02 PM
linux mysql php

The content of this article is about how PHP uses SwooleTaskWorker to implement asynchronous operation of Mysql (code). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

In general Server programs, there are some time-consuming tasks, such as sending emails, chat servers sending broadcasts, etc. If we use synchronous blocking waterproofing to perform these tasks, it will definitely be very slow.

Swoole's TaskWorker process pool can be used to perform some asynchronous tasks without affecting subsequent tasks, which is very suitable for handling the above scenarios.

So what is an asynchronous task?

You can get a brief understanding from the diagram below. (From the Internet, intrusion and deletion)

How does php use SwooleTaskWorker to implement asynchronous operation Mysql (code)

Our last Swoole article introduced how to create a simple server and knew a few cores How to use the callback function.

To implement the above asynchronous processing, you only need to add two event callbacks: onTask and onFinish. These two callback functions are used to execute Task tasks and process the return results of Task tasks respectively. In addition, you need to set the number of task processes in the set method.

Usage example:

class Server
{
    private $serv;
    public function __construct() {
        $this->serv = new swoole_server("0.0.0.0", 9501);
        $this->serv->set(array(
            'worker_num' => 4,
            'daemonize' => false,
            'task_worker_num' => 8
        ));
        $this->serv->on('Start', array($this, 'onStart'));
        $this->serv->on('Connect', array($this, 'onConnect'));
        $this->serv->on('Receive', array($this, 'onReceive'));
        $this->serv->on('Close', array($this, 'onClose'));
        $this->serv->on('Task', array($this, 'onTask'));
        $this->serv->on('Finish', array($this, 'onFinish'));
        $this->serv->start();
    }

    public function onReceive( swoole_server $serv, $fd, $from_id, $data ) {
        echo "Get Message From Client {$fd}:{$data}\n";
        // 发送任务到Task进程
        $param = array(
            'fd' => $fd
        );
        $serv->task( json_encode( $param ) );
        echo "继续处理之后的逻辑\n";
    }

    public function onTask($serv, $task_id, $from_id, $data) {
        echo "This Task {$task_id} from Worker {$from_id}\n";
        echo "Data: {$data}\n";
        for($i = 0 ; $i send( $fd , "Data in Task {$task_id}");
        return "Task {$task_id}'s result";
    }
    public function onFinish($serv,$task_id, $data) {
        echo "Task {$task_id} finish\n";
        echo "Result: {$data}\n";
    }
    public function onStart( $serv ) {
        echo "Server Start\n";
    }
    public function onConnect( $serv, $fd, $from_id ) {
        echo "Client {$fd} connect\n";
    }
    public function onClose( $serv, $fd, $from_id ) {
        echo "Client {$fd} close connection\n";
    }
}
$server = new Server();
Copy after login

As you can see from the above example, to initiate an asynchronous task, you only need to call the task method of swoole_server. After sending, the onTask callback will be triggered, and different tasks of different processes can be processed through $task_id and $from_id. Finally, the execution result can be returned to the Worker process by returning a string, and the Worker process processes the result through the onFinish callback.

Then based on the above code, asynchronous operation mysql can be realized. Asynchronous operation mysql is more suitable for the following scenarios:

  • Concurrent read and write operations

  • There is no strict relationship in timing

  • Does not affect the main thread logic

Benefits:

  • Improve concurrency

  • Reduce IO consumption

The pressure on the database mainly lies in the number of connections maintained by mysql. If there are 1,000 concurrencies, then mysql needs to establish a corresponding number of connections. With the long connection method, the MySQL connection is maintained in the process, reducing the loss of creating a connection. Multiple task processes can be started through swoole, and a MySQL long connection is maintained in each process. This can also be used to extend the MySQL connection pool technology. It should also be noted that if the mysql server detects that there has been no query for a long time, it will disconnect and recycle resources, so there must be a disconnection and reconnection mechanism.

The following is an example of a simple asynchronous operation mysql:

Still with the above code, we only need to modify the three functions onReceive, onTask and onFinish.

class Server
{
    private $serv;
    public function __construct() {
        $this->serv = new swoole_server("0.0.0.0", 9501);
        $this->serv->set(array(
            'worker_num' => 4,
            'daemonize' => false,
            'task_worker_num' => 8 // task进程数量 即为维持的MySQL连接的数量
        ));
        $this->serv->on('Start', array($this, 'onStart'));
        $this->serv->on('Connect', array($this, 'onConnect'));
        $this->serv->on('Receive', array($this, 'onReceive'));
        $this->serv->on('Close', array($this, 'onClose'));
        $this->serv->on('Task', array($this, 'onTask'));
        $this->serv->on('Finish', array($this, 'onFinish'));
        $this->serv->start();
    }

    public function onReceive( swoole_server $serv, $fd, $from_id, $data ) {
        echo "收到数据". $data . PHP_EOL;
        // 发送任务到Task进程
        $param = array(
            'sql' => $data, // 接收客户端发送的 sql 
            'fd'  => $fd
        );
        $serv->task( json_encode( $param ) );  // 向 task 投递任务
        echo "继续处理之后的逻辑\n";
    }

    public function onTask($serv, $task_id, $from_id, $data) {
        echo "This Task {$task_id} from Worker {$from_id}\n";
        echo "recv SQL: {$data['sql']}\n";
        static $link = null;
        $sql = $data['sql'];
        $fd  = $data['fd'];
        HELL:
        if ($link == null) {
            $link = @mysqli_connect("127.0.0.1", "root", "root", "test");
        }
        $result = $link->query($sql);
        if (!$result) { //如果查询失败
            if(in_array(mysqli_errno($link), [2013, 2006])){
                //错误码为2013,或者2006,则重连数据库,重新执行sql
                    $link = null;
                    goto HELL;
            }
        }
        if(preg_match("/^select/i", $sql)){//如果是select操作,就返回关联数组
             $data = array();
                while ($fetchResult = mysqli_fetch_assoc($result) ){
                     $data['data'][] = $fetchResult;
                }                
        }else{//否则直接返回结果
            $data['data'] = $result;
        }
        $data['status'] = "OK";
        $data['fd'] = $fd;
        $serv->finish(json_encode($data));
    }
    public function onFinish($serv, $task_id, $data) {
        echo "Task {$task_id} finish\n";
        $result = json_decode($result, true);
        if ($result['status'] == 'OK') {
            $this->serv->send($result['fd'], json_encode($result['data']) . "\n");
        } else {
            $this->serv->send($result['fd'], $result);
        }
    }
    public function onStart( $serv ) {
        echo "Server Start\n";
    }
    public function onConnect( $serv, $fd, $from_id ) {
        echo "Client {$fd} connect\n";
    }
    public function onClose( $serv, $fd, $from_id ) {
        echo "Client {$fd} close connection\n";
    }
}
$server = new Server();
Copy after login

The above code directly receives a sql during onReceive, and then sends it directly to the Task task. At this time, the next step of the process is output immediately, and asynchronousness is also reflected here. Then onTask and onFinish are used to send sql to the database and process the task execution results.

The above is the detailed content of How does php use SwooleTaskWorker to implement asynchronous operation Mysql (code). For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Linux Architecture: Unveiling the 5 Basic Components Linux Architecture: Unveiling the 5 Basic Components Apr 20, 2025 am 12:04 AM

The five basic components of the Linux system are: 1. Kernel, 2. System library, 3. System utilities, 4. Graphical user interface, 5. Applications. The kernel manages hardware resources, the system library provides precompiled functions, system utilities are used for system management, the GUI provides visual interaction, and applications use these components to implement functions.

MySQL and phpMyAdmin: Core Features and Functions MySQL and phpMyAdmin: Core Features and Functions Apr 22, 2025 am 12:12 AM

MySQL and phpMyAdmin are powerful database management tools. 1) MySQL is used to create databases and tables, and to execute DML and SQL queries. 2) phpMyAdmin provides an intuitive interface for database management, table structure management, data operations and user permission management.

Docker on Linux: Containerization for Linux Systems Docker on Linux: Containerization for Linux Systems Apr 22, 2025 am 12:03 AM

Docker is important on Linux because Linux is its native platform that provides rich tools and community support. 1. Install Docker: Use sudoapt-getupdate and sudoapt-getinstalldocker-cedocker-ce-clicotainerd.io. 2. Create and manage containers: Use dockerrun commands, such as dockerrun-d--namemynginx-p80:80nginx. 3. Write Dockerfile: Optimize the image size and use multi-stage construction. 4. Optimization and debugging: Use dockerlogs and dockerex

How to safely store JavaScript objects containing functions and regular expressions to a database and restore? How to safely store JavaScript objects containing functions and regular expressions to a database and restore? Apr 19, 2025 pm 11:09 PM

Safely handle functions and regular expressions in JSON In front-end development, JavaScript is often required...

The Compatibility of IIS and PHP: A Deep Dive The Compatibility of IIS and PHP: A Deep Dive Apr 22, 2025 am 12:01 AM

IIS and PHP are compatible and are implemented through FastCGI. 1.IIS forwards the .php file request to the FastCGI module through the configuration file. 2. The FastCGI module starts the PHP process to process requests to improve performance and stability. 3. In actual applications, you need to pay attention to configuration details, error debugging and performance optimization.

Explain the purpose of foreign keys in MySQL. Explain the purpose of foreign keys in MySQL. Apr 25, 2025 am 12:17 AM

In MySQL, the function of foreign keys is to establish the relationship between tables and ensure the consistency and integrity of the data. Foreign keys maintain the effectiveness of data through reference integrity checks and cascading operations. Pay attention to performance optimization and avoid common errors when using them.

CentOS: Security, Stability, and Performance CentOS: Security, Stability, and Performance Apr 21, 2025 am 12:11 AM

CentOS is the first choice for server and enterprise environments for its superior security, stability and performance. 1) Security provides forced access control through SELinux to improve system security. 2) Stability is supported by the LTS version for up to 10 years to ensure the stability of the system. 3) Performance significantly improves system response speed and resource utilization by optimizing kernel and system configuration.

How does MySQL differ from Oracle? How does MySQL differ from Oracle? Apr 22, 2025 pm 05:57 PM

MySQL is suitable for rapid development and small and medium-sized applications, while Oracle is suitable for large enterprises and high availability needs. 1) MySQL is open source and easy to use, suitable for web applications and small and medium-sized enterprises. 2) Oracle is powerful and suitable for large enterprises and government agencies. 3) MySQL supports a variety of storage engines, and Oracle provides rich enterprise-level functions.

See all articles