我需要在 Perl 中模块化 gearman 工作者,这样我就可以注册不同的工作者函数名称及其实现并重用所有其他代码。
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 模块的所有功能,除了我可以在不同的文件中注册不同的函数名称及其实现,例如:
模块G.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
}
你能帮我吗,我如何模块化这段代码。