继上篇 2018年swoole实战4-异步io读写
本篇演示 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, '科幻小说', '三体');
<?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, // 设置超时时间
];