think-orm-async tp orm 异步批量执行
<?php
declare (strict_types = 1);
namespace app\index\home;
use app\admin\model\Action;
use think\facade\Db;
use Yangweijie\ThinkOrmAsync\AsyncContext;
class Index extends Home
{
public function index()
{
// 默认跳转模块
if (config('app.home_default_module') != '' && config('app.home_default_module') != 'index') {
$this->redirect(config('app.home_default_module'). '/index/index');
}
if(input('type', 1) == 1){
Action::find(1);
Action::find(2);
Db::query("select sleep(1)");
Db::query("select sleep(1)");
Action::find(3);
Action::find(4);
Action::find(5);
Action::find(6);
Action::find(7);
Action::find(8);
Action::find(9);
Action::find(10);
$result4 = Action::find(3);
dump($result4);
}else{
// 配置数据库连接
// $dbConfig = config('database.connections.mysql');
// 开始异步上下文
// 开始异步上下文
AsyncContext::start();
// 原生查询 - 使用 AsyncContext::query()
$result1 = AsyncContext::query("SELECT sleep(1) as wait_time");
$result2 = AsyncContext::query("SELECT sleep(1) as wait_time");
$result3 = AsyncContext::query("SELECT NOW() as `current_time`");
$result4 = Action::find(3);
// 也可以混合使用 ORM 查询
// $users = User::where('status', 1)->select();
// 结束异步上下文,所有查询会并行执行
$results = AsyncContext::end();
// 获取结果
echo "Result 1: ";
var_dump($result1->toArray());
echo "Result 2: ";
var_dump($result2->toArray());
echo "Result 3: ";
var_dump($result3->toArray());
dump($result4->toArray());
echo "Total execution time: ~1 second (parallel execution)" . PHP_EOL;
}
return '123';
}
}
本质是多个链接,所以不支持事务, 参考 github.com/v10086/plan9/blob/main/...
php5.3 就支持了 需要 mysqli扩展支持 mysqli_poll 函数,包里已经判断环境了。laravel 也可以 参考生成一个包。
关于 LearnKu