My PHP website program calls the interface of an external website.
When the user inputs data, the PHP program will receive the data, then request the interface of the external website based on the data, obtain the data and return it to the user.
But when multiple users submit data at the same time, PHP will request that interface at the same time, and that interface will return an error.
Now I want to use PHP+Redis to make a queue. The user's request will be placed in the Redis queue and the external interfaces will be queried one by one to avoid the problem of requesting interfaces at the same time.
How to implement it specifically?
My PHP website program calls the interface of an external website.
When the user inputs data, the PHP program will receive the data, then request the interface of the external website based on the data, obtain the data and return it to the user.
But when multiple users submit data at the same time, PHP will request that interface at the same time, and that interface will return an error.
Now I want to use PHP+Redis to make a queue. User requests will be placed in the Redis queue and queried on the external interfaces one by one to avoid the problem of simultaneous request interfaces.
How to implement it specifically?
Try this
<code>// 创建请求ID标志, uniqid 无法保证唯一, 自己去搜索生成唯一的方法 $uuid = uniqid(); $tsk_name = "mytask"; $time_out = 30000; // 超时策略: 30秒 $time_start = time(); $redis->rPush($tsk_name, $uuid); // 右(后)插入队列 // 堵塞等待队列中第一个和$uuid匹配的(到我了) while($uuid != $redis->lGet($tsk_name, 0)){ if((time()-$time_start)> $time_out) { break; // 超时跳出(某些原因队列异常了, 可能永远取不到) } usleep(10); // sleep 10ms, 再次尝试 } // 这里执行任务的处理代码.... // $response 已拼装好要返回的内容 // 处理完成后(数据库等已入库更新), 需要: if($redis->lGet($tsk_name, 0) == $uuid){ // 再次确认第一个是本请求 $redis->lPop($tsk_name); // 完成任务了, 从队列中移除 } // 响应内容 return $response;</code>
Hand type has not been verified, the idea is this.