Gearman 和 inotify 用于任务执行

Gearman and inotify for tasks execution

我对如何在我的 php 应用程序中有效地使用 gearman 有一些疑问。

我正在使用 inotify 监视一个文件夹,其中将存储和处理大量文件(每次超过 1000 个)。 为了解析它们中的每一个并将其内容保存在数据库中,我正在尝试使用 gearman。

    while(true){
        sleep(5);   # spare some CPU Cycles
        set_time_limit(0); # unlimited timeout request 
        // read events 
        $events = inotify_read($this->instance);

        // if the event is happening within our 'Files directory'
            if ($events[0]['wd'] === $this->watch_id){              
                foreach ($events as $key=>$value)
                {
                    if($events[$key]['mask'] === IN_CREATE){
                        # A new file was created in folder                          
                        $client = new \GearmanClient();
                        $client->addServer();
                        $client->addTask("parse_file", $events[$key]['name']);  # add task to parse that file
                        printf("Created file: %s in Files directory\n", $events[$key]['name']);
                    }
                    else if ($events[$key]['mask'] === IN_DELETE){
                        printf("Deleted file: %s in Files directory\n", $events[$key]['name']);
                    }                           
                }
                if(!is_null($client)){  # once everything is done, run the tasks.   
                    $client->runTasks();                
                }
            }
    }

我创建了一个 worker.php 文件,如下所示:

<?php
namespace controllers;
use app\file\File;
require_once 'vendor/autoload.php';

$worker = new \GearmanWorker();
$worker->addServer();
$worker->addFunction('parse_file', function($job){
    echo "entrou no add function!<br>";
    print_r ($job->workload());
    sleep(2);
    return new File($job->workload()); # this class parses the files content in database
});                     
while ($worker->work());

事情正在发生。 worker函数运行,第一个文件的数据存入数据库,但出现错误:

这是我的 nohup.out 文件的输出。

Catchable fatal error: Object of class app\file\File could not be converted to string in /var/www/html/worker.php on line 18 

"he"想要什么? :)

我设法解决了问题的最后一部分。

错误:

Catchable fatal error: Object of class app\file\File could not be converted to string in /var/www/html/worker.php on line 18 

是因为我在这里返回一个对象:

sleep(2);
    return new File($job->workload()); # this class parses the files content in database

在我的工作函数中不返回任何东西碰巧修复了错误。需要更好地研究 Gearman 以及如何为 运行 我的代码创建更多工人。

仅作记录:如果您尝试将工作人员连接到远程 gearman 作业服务器,您可能会遇到麻烦。 要允许远程连接,您必须更改位于 /etc/default/gearman-job-server:

的 gearman-server 配置中的监听端口
# Parameters to pass to gearmand.
PARAMS=""

请注意,如果您在 public 网络中使用此服务器,则服务器完全可以从任何地方进行远程连接。