Closed stonegithubs closed 1 year ago
给个完整的代码,有空我试试
给个完整的代码,有空我试试 在协程代码中只有Db更新操作
<?php
declare(strict_types=1);
namespace app\command;
use think\facade\Db;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use think\swoole\command\Swoole;
use Swoole\Coroutine\WaitGroup;
use Swoole\Coroutine\Channel;
use function Swoole\Coroutine\go;
class Test extends Swoole
{
protected function configure()
{
// 指令配置
$this->setName('swoole:test')
->addOption(
'env',
'E',
Option::VALUE_REQUIRED,
'Environment name',
''
)
->setDescription('the swoole test command');
}
protected function runInSwoole(Input $input, Output $output)
{
$wg = new WaitGroup();
// 用channel控制并发数量,config/swoole里面配置'max_active' => 64,
$chan = new Channel(64);
for ($c = 10000; $c--;) {
$wg->add();
$chan->push(true);
go(function () use ($wg, $chan) {
Db::transaction(function () use ($wg, $chan) {
try {
Db::name('product')->where('id',1)->update(['name' => 'abc']);
} catch (\Throwable $e) {
echo 'error: ' . $e->getMessage(), PHP_EOL;
} finally {
$chan->pop();
$wg->done();
}
});
});
}
$wg->wait();
echo 'ok', PHP_EOL;
}
}
给个完整的代码,有空我试试
非常感谢你提供的办法,之前批量操作数据,都是一条一条更新,用上你给的代码可以多个协程,速度快多了
Originally posted by @he426100 in https://github.com/top-think/think-swoole/issues/331#issuecomment-1382635656 在think-swoole中新增CommandManager.php,SwooleCommand.php,在command目录添加以上代码测试会遇到以下问题
环境:php8.2.8,Ubuntu20.04,thinkphp8.0.2,think-swoole4.0.11