本篇演示 swoole的异步mysql
模拟数据
在本地test数据库中新建book表,写入模拟数据
CREATE TABLE `book`
`id` int(11) NOT NULL AUTO_INCREMENT,
`content` text,(
`titlle` varchar(255) NOT NULL COMMENT '标题',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
insert into book value (1, '科幻小说', '三体');
异步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) {
// 连接失败
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 '执行成功' . PHP_EOL;
$db->close();
});
} catch (\Swoole\Mysql\Exception $e) {
echo $e->getMessage();
}
return true;
}
}
$obj = new AsyMysql();
$flag = $obj->execute(1,'大刘写的科幻小说');
echo "开始执行" . PHP_EOL;
执行结果
☁ async php mysql.php
开始执行
执行成功
[2018-07-27 15:24:27 @65638.0] TRACE [THREAD #0]EP=3|FD=4
连接时长
默认情况下,mysql的等待连接时长为1秒,超时会报错,如在代码最后加上
$obj = new AsyMysql();
$flag = $obj->execute(1,'大刘写的科幻小说');
echo "开始执行" . PHP_EOL;
sleep(3); // 暂停3秒
连接超时
通过设置超时时间可解决该问题:
$this->config = [
'host' => '127.0.0.1',
'port' => '3306',
'user' => 'root',
'password' => '',
'database' => 'test',
'charset' => 'utf8',
'timeout' => 5, // 设置超时时间
];
如果觉得本文对你有所帮助,点个赞,或者赏杯咖啡钱,你的认可对我很重要
网友评论