ギアマンワーカーを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
}
このコードをモジュール化するにはどうすればよいですか。