hyperf框架在普通的接口查询会出现多个,有必要使用协程吗?

已开启一键协程

如下代码

public function getInfo(string $hehe, int $uid = 0): array
{
    $data = [
        'info' => [],
        'num' => [
            'all' => 0,
            'col1' => 0,
            'col2' => 0,
            'col3' => 0,
        ],
    ];
    $w = W::where('w', '=', $hehe)->first();
    if (!$w) {
        return $data;
    }

    $time = time();
    if ($time >= $w->b_start_time && $time < $w->b_end_time) {
        // 这里有必要协程处理吗?
        $data['num']['col1'] = Col1::where('w', '=', $hehe)->count();
    }
    if ($time >= $w->e_start_time) {
        // 这里有必要协程处理吗?
        $userIds = All::where('w', '=', $hehe)->pluck('uid');
        if ($userIds) {
            $data['num']['all'] = \count(array_unique($userIds->toArray()));
        }
    }
    // 这里有必要协程处理吗?
    parallel([
        function () use (&$data, $season) {
            $col2Ids = Col2::where('w', '=', $hehe)
                ->where('type', '=', Col2::TYPE_1)
                ->pluck('uid');
            if ($col2Ids) {
                $data['num']['col2'] = count(array_unique($col2Ids->toArray()));
            }
            unset($teamUserIds);
        },
        function () use (&$data, $season) {
            $col3Ids = Col3::where('w', '=', $hehe)
                ->where('type', '=', Col3::TYPE_2)
                ->pluck('uid');
            if ($col3Ids) {
                $data['num']['col3'] = count(array_unique($col3Ids->toArray()));
            }
            unset($col3Ids);
        }
    ]);
    $data['info'] = $w->toArray();

    return $data;
}

return $data后,就直接response回去了

请问各位大佬们,代码中标注的地方有必要加协程处理吗?能说下具体的原因就更好了

讨论数量: 8

没啥必要, 这里就两个查询, 提升也不会很多. 如果有20个, 200个查询, 可以用来提升接口效率

3个月前 评论
FatTiger (楼主) 2个月前

没必要 写那么乱过两个月去维护的时候骂爹骂娘

3个月前 评论
FatTiger (楼主) 2个月前
zds

foreach可以

3个月前 评论
FatTiger (楼主) 2个月前

如果数据量较大,查询比较复杂,使用协程处理可以显著提高并发性能,避免阻塞其他请求。建议使用协程 Parallel 特性來控制并发

...
$parallel = Parallel(4);

$parallel->add(function(){
return Col1::where('w', '=', $hehe)->count();
},'col1');

$parallel->add(function(){
return All::where('w', '=', $hehe)->pluck('uid')->unique()->count();
},'all');

$parallel->add(function(){
return Col2::where('w', '=', $hehe)
                ->where('type', '=', Col2::TYPE_1)
                ->pluck('uid')->unique()->count();
},'col2');

$parallel->add(function(){
return  Col3::where('w', '=', $hehe)
                ->where('type', '=', Col3::TYPE_2)
                ->pluck('uid')->unique()->count();
},'col3');

$data['num']  = $parallel = wait();
$data['info'] = $w->toArray();
return $data;
2个月前 评论
FatTiger (楼主) 2个月前

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