think-orm-async tp orm 异步批量执行

AI摘要
【知识分享】该内容展示了PHP框架ThinkPHP中利用think-orm-async包实现数据库异步查询的技术方案。通过AsyncContext上下文,可将多个原生SQL查询(如SELECT sleep(1))并行执行以提升性能,并说明了其基于mysqli_poll实现、不支持事务及对Laravel的参考价值。

think-orm-async

<?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 也可以 参考生成一个包。

yangweijie
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!