如何打开多个套接字连接并在PHP中执行回调 [英] How to open multiple socket connections and do callbacks in PHP

查看:111
本文介绍了如何打开多个套接字连接并在PHP中执行回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在写一些代码来处理一个项目的队列。它的工作方式是这样的:


  1. 获取下一个项目标记为需要
    从mysql
    数据库行。

  2. 使用Curl从Google API请求一些信息
    ,等待信息为



  3. db中标记处理的项目,移动到下一个项目。

问题是在步骤#2,Google有时需要10-15秒才能返回请求的信息,在此期间我的脚本必须保持暂停并等待。



我想知道是否可以改变代码来执行以下操作:


  1. 照常处理

  2. 请从
    google一个接一个地请求项目1-5的信息。

  3. 当项目1的信息是
    返回时,'callback'应该是
    done,它调用一个函数或
    否则调用一些代码然后
    处理项目1-5上的
    的剩余部分。

  4. 然后脚本从
    开始,直到db中的所有挂起项都是$ b $

    >解决方案

    您可以在两种流程类型中拆分。


    1. 的用户正在运行):知道正在处理的数据库行,并等待Google API调用,然后执行作业,并将结果保存到数据库。


    2. p>调度程序(一个和唯一):定期(例如,每几秒钟)检查是否有工作要做,并确保有N(5或任何最佳)工人运行。如果少于N个工人正在运行,则启动更多工人( exec )以保持N,直到所有工作完成。



    I'm writing some code which processes a queue of items. The way it works is this:

    1. Get the next item flagged as needing to be processed from the mysql database row.
    2. Request some info from a google API using Curl, wait until the info is returned.
    3. Do the remainder of the processing based on the info returned.
    4. Flag the item as processed in the db, move onto the next item.

    The problem is that on step # 2. Google sometimes takes 10-15 seconds to return the requested info, during this time my script has to remain halted and wait.

    I'm wondering if I could change the code to do the following instead:

    1. Get the next 5 items to be processed as usual.
    2. Request info for items 1-5 from google, one after the other.
    3. When the info for item 1 is returned, a 'callback' should be done which calls up a function or otherwise calls some code which then does the remainder of the processing on items 1-5.
    4. And then the script starts over until all pending items in db are marked processed.

    How can something like this be achieved?

    解决方案

    You can split this in 2 process types.

    1. Worker process (there are many of them running): knows the database row being processed, makes and waits for Google API call, and then does the job, and saves the results to the database.

    2. Scheduler (one and only): periodically (say, every few seconds) checks if there's work to do, and makes sure that there are N (5 or whatever is optimal) workers running. If less then N workers are running, starts more workers (with exec) to keep it N, until all the work is done.

    这篇关于如何打开多个套接字连接并在PHP中执行回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆