我需要在Perl中模拟齿轮工作者,这样我就可以注册不同的工作者函数名称及其实现,并重用所有其他代码。
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 "%s\n", $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 "%s\n", $worker->error());
}
#----------------------------------------------------------------------
# Wait for job
#----------------------------------------------------------------------
while (1)
{
my $ret = $worker->work();
if ($ret != GEARMAN_SUCCESS)
{
printf(STDERR "%s\n", $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 host\n");
printf("\t-p <port> - job server port\n");
printf("\t-t <timeout> - timeout in milliseconds\n");
}
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
}
您能帮助我吗,我该如何模块化这段代码。
答案 0 :(得分:2)
它与php非常相似。
将德语连接代码拆分为.pm文件
将package ModuleG;
添加到顶部,1;
添加到文件底部
在ModuleG.pm中创建一个函数来访问worker
Sub worker { return $worker; }
因为从模块公开变量被认为是不好的做法
将工作人员调用为ModuleG->worker()->add_function("do_new_work", 0, \&do_new_work, '');
并将子定义为正常。