[英]How to open multiple socket connections and do callbacks in PHP
I'm writing some code which processes a queue of items. 我正在编写一些代码来处理一系列项目。 The way it works is this: 它的工作方式是这样的:
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. 问题在于步骤2。Google有时需要10到15秒才能返回请求的信息,在此期间,我的脚本必须保持暂停状态并等待。
I'm wondering if I could change the code to do the following instead: 我想知道是否可以更改代码以执行以下操作:
How can something like this be achieved? 这样的事情怎么实现?
You can split this in 2 process types. 您可以将其分为2个过程类型。
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. 辅助进程(其中有许多正在运行):知道正在处理的数据库行,进行并等待Google API调用,然后执行作业,并将结果保存到数据库中。
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. 调度程序(仅一个):定期(例如,每隔几秒钟)检查是否有工作要做,并确保正在运行N(5个或最佳的工作)工人。 If less then N workers are running, starts more workers (with exec
) to keep it N, until all the work is done. 如果正在运行的工人少于N个,则(使用exec
)启动更多工人以使其保持N,直到完成所有工作为止。
I really don't know if this is an elegant approach, but in theory you could use fork() to fork the PHP process for each item. 我真的不知道这是否是一种优雅的方法,但是从理论上讲,您可以使用fork()为每个项目派生PHP进程。 This would allow all code to be in one file. 这将允许所有代码都在一个文件中。
// Get items from DB
$items = get_items_from_db();
foreach($items as $item) {
$pid = pcntl_fork();
if($pid == -1) die("Couldn't fork!");
if(!$pid) {
// Process the item in the child process
process_item($item);
exit();
}
}
// Wait for all child processes to end
pcntl_wait();
// We're done!
But yes, this solution will most likely make some people scream ;) 但是,是的,这种解决方案很可能会使某些人尖叫;)
I think you can create a master script that will call a child script on same machine for a particular item. 我认为您可以创建一个主脚本,该脚本将在同一台计算机上针对特定项目调用子脚本。 The child script will send request to google API and work accordingly. 子脚本将请求发送到Google API并相应地工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.