2018 swoole actual combat 5-asynchronous mysql

Following the last chapter 2018 swoole 4-asynchronous io reading and writing

This presentation Asynchronous mysql of swoole

Analog data

Create a new book table in the local test database and write the simulation data

CREATE TABLE `book` 
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `content` text,(
  `titlle` varchar(255) NOT NULL COMMENT 'Title',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

insert into book value (1, 'science fiction', 'Trisomy');

Asynchronous mysql

<?php
class AsyMysql {
    public $db;
    public $config = [];
    public function __construct()
    {
        $this->db = new swoole_mysql();
        $this->config = [
            'host' => '127.0.0.1',
            'port' => '3306',
            'user' => 'root',
            'password' => '',
            'database' => 'test',
            'charset' => 'utf8',
        ];
    }

    public function execute($id, $content) {
        try {
            $this->db->connect($this->config, function ($db, $result) use ($id, $content) {
                if ($result === false) {
                    // connection failed
                    var_dump($db->connect_error);
                }
                $sql = "update book set `content` = '{$content}' where id = {$id}";
                $db->query($sql, function ($db, $result) {
                    if ($result === false) {
                        var_dump($db->error);
                    } else if ($result === true) {
                        var_dump($db->affected_rows);
                    } else {
                        var_dump($result);
                    }
                });
                echo 'Successful implementation' . PHP_EOL;
                $db->close();
            });
        } catch (\Swoole\Mysql\Exception $e) {
            echo $e->getMessage();
        }

        return true;
    }
}

$obj = new AsyMysql();
$flag = $obj->execute(1,'Science fiction written by Liu Da');
echo "Start execution" . PHP_EOL;

results of enforcement

☁  async  php mysql.php
 Start execution
 Successful implementation
[2018-07-27 15:24:27 @65638.0]  TRACE   [THREAD #0]EP=3|FD=4

Connection duration

By default, the waiting time for mysql to connect is 1 second, and an error will be reported in case of timeout, such as adding

$obj = new AsyMysql();
$flag = $obj->execute(1,'Science fiction written by Liu Da');
echo "Start execution" . PHP_EOL;
sleep(3); // Pause for 3 seconds.
connection timed out

The problem can be solved by setting the timeout:

$this->config = [
    'host' => '127.0.0.1',
    'port' => '3306',
    'user' => 'root',
    'password' => '',
    'database' => 'test',
    'charset' => 'utf8',
    'timeout' => 5, // Set timeout
];

If you think this article is helpful to you, like it or enjoy a cup of coffee money, your recognition is very important to me

Tags: MySQL Database PHP SQL

Posted on Fri, 31 Jan 2020 00:22:51 -0800 by Rai_de