写篇小Tips,纪念我们逝去的爱情.
最近有需要批量请求网址进行一些操作,使用了guzzle.官方文档不甚详细,这里自己补充一点,以便自己日后翻看
官网文档
$client = new Client(); //使用闭包函数,将数据传入 $requests = function () use ($client,$ids,$url) { foreach ($ids as $user) { $arr = explode('|',$user); yield function() use ($client, $url,$arr) { //return $client->getAsync($url); return $client->postAsync($url,[RequestOptions::JSON=>[ 'openId' => $arr[1], 'appId' => 123, 'accessToken' => $arr[2], ]]); }; } }; //使用连接池进行处理 $pool = new Pool($client, $requests(), [ 'concurrency' => 100,//每轮进行100个请求 'fulfilled' => function ($response, $index) use ($ids){ //请求成功之后进行的一些数据处理 Facade::system()::public_log("请求第 $index 个请求,用户 " .kimoo_date('Y-m-d H:i:s'), 'friend'); $curr = $ids[$index]; $arr = explode('|',$curr); $ddl_id = $arr[0]; $xtc_openid = $arr[1]; $token = $arr[2]; $res = (array)json_decode($response->getBody()->getContents(), true); if ($res['code'] != '000001') { $msg = "tran_xtc_friend err {$res['code']} {$res['desc']} id:$ddl_id openid:$xtc_openid token:$token"; Facade::system()::public_log($msg, 'friend'); return; } $list = $res['data'];//好友的列表 $friend_ids = []; foreach ($list as $friend) { $old_openid = get_old_openid($friend['openId']); $short_id = idlong2short($old_openid); if(!$short_id){ $short_id = $friend['openId']; } debug_log('get_userinfos_by_openids ' . $short_id); $target_ddlid = get_ddlid_by_account('xtc', $short_id); if (empty($target_ddlid)) { $new_openid = get_new_openid($friend['openId']); $target_ddlid = get_ddlid_by_account('xtc', $new_openid); } if (empty($target_ddlid)) { continue; } $friend_ids[] = $target_ddlid.'|'.kimoo_time().'|xtc'; //获取的时候就通知进行一下更新,为了数据及时 $this->redisToDb($target_ddlid); } if (!empty($friend_ids)) { $redis = get_redis_cli_by_name(PET_REDIS_NAME); $key = $ddl_id . '_xtc_phone_friend_list'; $redis->del($key); $redis->sAddArray($key, $friend_ids); $msg = "tran_xtc_friend success id:$ddl_id openid:$xtc_openid token:$token"; Facade::system()::public_log($msg, 'friend'); } }, 'rejected' => function ($reason, $index) use ($ids) { //请求失败进行的一些数据处理 $curr = $ids[$index]; $arr = explode('|',$curr); $ddl_id = $arr[0]; $xtc_openid = $arr[1]; $token = $arr[2]; $msg = "tran_xtc_friend err id:$ddl_id openid:$xtc_openid token:$token 本轮第{$index}个用户请求失败,失败原因 $reason"; Facade::system()::public_log($msg, 'friend'); }, ]); // 开始发送请求 $promise = $pool->promise(); $promise->wait(); Facade::system()::public_log('本轮处理结束'.kimoo_date('Y-m-d H:i:s'), 'friend');
好了,写完了,单身就是这么无聊,再见
0 条评论