My PHP Site program calls an interface to an external Web site.
When the user enters the data, the PHP program receives the data, and then requests the interface of that external website based on the data to get the data back to the user.
But when multiple users commit data at the same time, PHP requests that interface at the same time, and that interface returns an error.
I now want to use Php+redis to make a queue, the user's request will be placed in the Redis queue, one by one to the external interface query, to avoid the simultaneous request interface problems.
How to achieve it?
Reply content:
My PHP Site program calls an interface to an external Web site.
When the user enters the data, the PHP program receives the data, and then requests the interface of that external website based on the data to get the data back to the user.
But when multiple users commit data at the same time, PHP requests that interface at the same time, and that interface returns an error.
I now want to use Php+redis to make a queue, the user's request will be placed in the Redis queue, one by one to the external interface query, to avoid the simultaneous request interface problems.
How to achieve it?
Give it a try.
// 创建请求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;
Hand hit unverified, the idea is this.