如何构建一个PHP队列系统

12

我需要建立一个PHP队列系统,找到了这篇绝妙的文章http://squirrelshaterobots.com/programming/php/building-a-queue-server-in-php-part-1-understanding-the-project,并使用它创建了一个PHP队列系统,非常容易设置和使用。

以下是queue.php的代码,从shell(puTTy或类似工具)运行。

<?PHP 

//. set this constant to false if we ever need to debug
//. the application in a terminal.
define('QUEUESERVER_FORK', true);

//////// fork into a background process ////////
if(QUEUESERVER_FORK){    
    $pid = pcntl_fork(); 
    if($pid === -1) die('error: unable to fork.');    
    else if($pid) exit(0);        
    posix_setsid();    
    sleep(1);        
    ob_start();
}

$queue = array();

//////// setup our named pipe ////////
$pipefile = '/tmp/queueserver-input';

if(file_exists($pipefile))    
    if(!unlink($pipefile))         
        die('unable to remove stale file');

umask(0);


if(!posix_mkfifo($pipefile, 0666))    
    die('unable to create named pipe');

$pipe = fopen($pipefile,'r+');

if(!$pipe) die('unable to open the named pipe');

stream_set_blocking($pipe, false);

//////// process the queue ////////
while(1){    

    while($input = trim(fgets($pipe))){        
        stream_set_blocking($pipe, false);        
        $queue[] = $input;    
    }    

    $job = current($queue);    
    $jobkey = key($queue);    

    if($job){        
        echo 'processing job ', $job, PHP_EOL;                
        process($job);                
        next($queue);        
        unset($job, $queue[$jobkey]);            
    }else{        
        echo 'no jobs to do - waiting...', PHP_EOL;        
        stream_set_blocking($pipe, true);    
    }        

    if(QUEUESERVER_FORK) ob_clean();

}

?>

最难的部分是让pcntl函数在我的服务器上正常工作。

我的问题是“如果/当服务器必须重新启动,如何使作业自动启动?”


如评论中所述,编辑了破损链接并为后世指向了极好的Web存档。


1
你的问题到底是什么? - Martin Bean
1
@MartinBean 当/如果服务器需要重新启动时,如何使作业自动启动? - Folding Circles
1
你可以修改服务器启动脚本来实现这一点,或者添加一个报告脚本/服务器状态的脚本和一个重新启动作业的脚本,然后在本地或远程主机上使用它们来监视服务器/重新启动作业(使用cronjob)。 - llamerr
@Calos 请记住,如果要使用pcntl_*()函数运行PHP脚本,则必须将PHP作为CGI运行,如果作为Apache模块运行,则不允许命令行使用。 - cryptic ツ
1
@Calos,你有那篇精彩的文章保存吗?网站好像挂了,而那篇文章正是我个人所需要的 :) - Webeng
2
这是一篇非常棒的文章 - 我为了很好的理由将其加入了书签。我认为这个链接现在是我们最好的选择 - 2016年1月份的版本可用。 - TacoV
1个回答

11
我的问题是“如果服务器需要重新启动,如何使工作自动开始?”将其添加到服务器启动时启动的事物列表中。不幸的是,这样做的说明因操作系统和操作系统版本而异。您可能希望使用更跨平台的东西。我已经在supervisor上取得了很大的成功,您可以在所选操作系统的软件包存储库中找到它。
话虽如此,您正在走向疯狂的路线。你正在做的事情已经被一些厉害的人做过,并且做得更好。看看Gearman工作队列系统和相应的PECL扩展。恰好supervisor也非常有用,可以让您的Gearman工作者保持活动状态。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接