前言:需要的注意的是,如果swoole版本在4.3以上,我们就不能够使用Async文档中的异步协程回调了!
而替代上方的Async文档的Coroutine文档,我们打开官网的Coroutine的选项,进入到异步mysql的相关文档中
1.这里也有一个坑,可能是文档没有描述清楚,我们如果按照上面的下面的这个demo是无法使用的,会报错
笔者在这里折腾了一个多小时,终于找到了方法,需要在协程方法中实现该方法,我们上代码
co::create(function() {
$swoole_mysql = new Swoole\Coroutine\MySQL();
$swoole_mysql->connect([ 'host' => 'XXXXX', 'port' => 3306, 'user' => 'root', 'password' => 'XXXX', 'database' => 'swoole', ]);
$res = $swoole_mysql->query('select sleep(1)');
var_dump($res);
});
使用以上方法,则能够正常运行
- 我们稍微将代码改进成面向对象的方式
<?php
//异步连接mysql
/**
*
*/
class connect
{
protected $config =[ 'host' => '127.0.0.1','port' => 3306,'user' => 'swoole','password' => 'woshichaoren1319','database' => 'swoole'];
protected $source ='';
/**
* 初始化对象
*/
function __construct()
{
$this->source = new Swoole\Coroutine\MySQL();
}
/**
* 新增操作
*/
public function add(){
co::create(function(){
$this->source->connect($this->config);
if ($this->source->connected) {
echo "连接成功\n";
}else{
echo "连接失败\n";
}
$res= $this->source->query('insert into duo_user (username,create_time) values ("duoduo",now())');
if ($res) {
echo "新增成功";
}
});
}
/**
* 更新操作
*/
public function upd(){
co::create(function(){
$this->source->connect($this->config);
if ($this->source->connected) {
echo "连接成功\n";
}else{
echo "连接失败\n";
}
$res= $this->source->query('update duo_user set status = 1 where status = 0');
if ($res) {
echo "更新成功";
}
});
}
public function del(){
co::create(function(){
$this->source->connect($this->config);
if ($this->source->connected) {
echo "连接成功\n";
}else{
echo "连接失败\n";
}
$res= $this->source->query('delete from duo_user where id < 5');
if ($res) {
echo "删除成功";
}
});
}
public function find(){
co::create(function(){
$this->source->connect($this->config);
if ($this->source->connected) {
echo "连接成功\n";
}else{
echo "连接失败\n";
}
$res= $this->source->query('select * from duo_user order by id desc limit 1 ');
var_dump($res).PHP_EOL;
if ($res) {
echo "查询成功";
}
});
}
}
$res = new connect();
$res->find();