swoole-异步mysql

前言:需要的注意的是,如果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);

});

使用以上方法,则能够正常运行

  1. 我们稍微将代码改进成面向对象的方式
<?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();
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值