在Perl中模块化Gearman工人



我需要在Perl中模块化gearman worker,这样我就可以注册不同的worker函数名和它们的实现,并重用所有其他代码。

use strict;
use warnings;
use Getopt::Std;
use JSON qw( decode_json );
use FindBin qw($Bin);
use lib ("$Bin/../blib/lib", "$Bin/../blib/arch");
use Gearman::XS qw(:constants);
use Gearman::XS::Worker;
my %opts;
if (!getopts('h:p:t:', %opts))
{
    usage();
    exit(1);
}
if(!defined($opts{h})) {
    usage();
    exit(1);
}
my $host    = $opts{h} || '';
my $port    = $opts{p} || 4730;
my $timeout = $opts{t} || -1;
my $worker= new Gearman::XS::Worker;
if ($timeout >= 0)
{
    $worker->set_timeout($timeout);
}
my $ret= $worker->add_server($host, $port);
if ($ret != GEARMAN_SUCCESS)
{
    printf(STDERR "%sn", $worker->error());
    exit(1);
}
#----------------------------------------------------------------------
# Register function
#----------------------------------------------------------------------
$ret= $worker->add_function("do_work", 0, &do_work, ''); # <-- 1. This function name can be changed
if ($ret != GEARMAN_SUCCESS)
{
    printf(STDERR "%sn", $worker->error());
}
#----------------------------------------------------------------------
# Wait for job
#----------------------------------------------------------------------
while (1)
{
    my $ret = $worker->work();
    if ($ret != GEARMAN_SUCCESS)
    {
        printf(STDERR "%sn", $worker->error());
    }
}
#----------------------------------------------------------------------
# Worker Function
#----------------------------------------------------------------------
sub do_work {   # 2. And then this implementation can be changed
    my $job         = shift;
    my $result      = '';
    my $workload    = $job->workload();
    my $params      = decode_json $workload;
    my $input_file  = $params->{'inFile'};
    my $output_file = $params->{'outFile'};
    my $options     = $params->{'options'};
    my $timeout     = $params->{'timeout'};
    # Worker code
    my $ret= $job->send_status(1, 1);
    if ($ret != GEARMAN_SUCCESS)
    {
        return '';
    }
    return $result;
}
#----------------------------------------------------------------------
# Usage
#----------------------------------------------------------------------
sub usage {
    printf("nusage: %s [-h <host>] [-p <port>]n", $0);
    printf("t-h <host>    - job server hostn");
    printf("t-p <port>    - job server portn");
    printf("t-t <timeout> - timeout in millisecondsn");
}
exit;

我想重用使用Perl模块的所有功能,除了我可以在不同的文件中注册不同的函数名称及其实现,例如:

ModuleG.php

# All the gearman connection and common code goes here

WorkerFunction.php

Use ModuleG
$SomeVAR = $worker->add_function("do_new_work", 0, &do_new_work, '');
do_new_work() {
    # code goes here
}

你能帮我一下,我怎么模块化这个代码

这与php非常相似。

  1. 将德语连接代码拆分为。pm文件

  2. package ModuleG;添加到文件的顶部,1;添加到文件的底部

  3. 在ModuleG中创建一个函数。PM访问工人Sub worker { return $worker; },因为从模块中暴露变量被认为是不好的做法

  4. 调用工作子为ModuleG->worker()->add_function("do_new_work", 0, &do_new_work, '');,定义子为normal

相关内容

  • 没有找到相关文章

最新更新