Ask Php+redis the idea of realizing task queue

Source: Internet
Author: User
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.

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.