Hyperf协程中再开协程,如何控制不超过max_connection

325 阅读1分钟

image.png hyperf.wiki/3.0/#/zh-cn…

max_connections 设置为 10

  • databases.php
......

'pool' => [  
    'min_connections' => 1,  
    'max_connections' => 10,  
    'connect_timeout' => 10.0,  
    'wait_timeout' => 3.0,  
    'heartbeat' => -1,  
    'max_idle_time' => (float) env('DB_MAX_IDLE_TIME', 60),  
],

......

循环创建协程中,再使用Parallel 开协程,如何设置,才能保证不超过连接池数量?

public function temp($i)  
{  
    $parallel = new Parallel(10);  // A ????????????????????

    $apiList = $this->getApiList();  
    foreach ($apiList as $api) {  
        // 开启协程  
        $parallel->add(function () use ($api) {  
            $res = $this->requestList($api['id']);  
            return true;  
        });  
    }  
}  
  
public function requestList($id)  
{  
    $parallel = new Parallel(10);   // B ????????????????????
    
    for ($i = 0; $i < 50; $i++) {  
    $params['page'] = $i;  
    $parallel->add(function () use ($params) {  
        $resp = $this->apiRequest->request('GET', $this->url, [  
            \GuzzleHttp\RequestOptions::FORM_PARAMS => $params,  
            \GuzzleHttp\RequestOptions::VERIFY => false,  
            \GuzzleHttp\RequestOptions::TIMEOUT => 30,
        ]);  
    });  
}  

A是外层循环的协程个数,B是内层循环,如何设置,才能保证不超过连接池 max_connection 数量


解答: