一、PHP Fatal error: Uncaught Error: Class ‘swoole_mysql’ not found in xxx
这个错误是因为用了异步回调模块,swoole 4.3.0版本后已经移除了异步模块,所以会报错没有找到swoole_mysql模块,用Swoole\Mysql一样报错。
解决方案:
1、用Corotuine协程模块代替
2、回退到旧版本swoole(不推荐)
二、PHP Fatal error: Uncaught Swoole\Error: operation not support (reactor is not ready) in xxxxxx
报这个错是因为没有用协程方式运行脚本,而直接用了php运行,需要在代码外面套个go(function(){ …这里写内容},才能正常运行!
附上本人代码:
<?php
class Mymysql{
// 数据库实例
public $dbSource = '';
// 数据库连接配置
public $server = [];
// 初始化参数
public function __construct()
{
$this->dbSource = new Swoole\Coroutine\MySQL();
$this->server = [
'host' => '127.0.0.1',
'port' => 3306,
'user' => 'swoole',
'password' => 'xxxxxxxxxxx',
'database' => 'swoole',
'charset' => 'utf8', //指定字符集
'timeout' => 2, // 可选:连接超时时间(非查询超时时间),默认为SW_MYSQL_CONNECT_TIMEOUT(1.0)
];
}
/**
* 执行逻辑
* @param $id
* @param $username
*/
public function execute(){
// 连接
go(function (){
$this->dbSource->connect($this->server);
$res = $this->dbSource->query('select * from test');
if($res === false) {
return;
}
var_dump($res);
// 关闭连接
$this->dbSource->close();
});
}
}
$obj = new Mymysql();
$obj->execute();
运行成功