From 5bd01740ee26507e173224f341cdfe85eba82d53 Mon Sep 17 00:00:00 2001 From: Pedro Melo Date: Mon, 21 Jul 2014 05:10:39 +0100 Subject: [PATCH] Improve consumer.pl: * use Getopt::Long to enable/disable help, verbose and print mode; * add proper usage message; * keep track of total messages received. Signed-off-by: Pedro Melo --- examples/consumer.pl | 43 ++++++++++++++++++++++++++++++++++++------- 1 file changed, 36 insertions(+), 7 deletions(-) diff --git a/examples/consumer.pl b/examples/consumer.pl index 999f2e9..cfee71e 100755 --- a/examples/consumer.pl +++ b/examples/consumer.pl @@ -6,24 +6,53 @@ use FindBin; use lib "$FindBin::Bin/../lib"; use AnyEvent; use AnyEvent::NSQ::Reader; +use Getopt::Long; -my ($topic, $channel) = @ARGV; -die "Usage: consumer.pl topic channel\n" unless $topic and $channel; +my ($topic, $channel, $help, $verbose, $print); +GetOptions('help' => \$help, 'verbose' => \$verbose, 'print' => \$print) or usage(); +usage() if $help; + +($topic, $channel) = @ARGV; +usage("topic and channel are required parameters") unless $topic and $channel; my $cv = AE::cv; -my $c = 1; +## return undef => mark_as_done_msg() +my $message_cb = $print ? sub { print "$_[1]{message}\n"; return } : sub {return}; + +my $t = 0; my $r = AnyEvent::NSQ::Reader->new( topic => $topic, channel => $channel, nsqd_tcp_addresses => '127.0.0.1', client_id => "${channel}_consumer/pid_$$", -# message_cb => sub { print STDERR "$c: $_[1]{message}\n"; $c++; return }, ## return undef => mark_as_done_msg() - message_cb => sub {return}, ## return undef => mark_as_done_msg() + message_cb => sub { $t++; $message_cb->(@_, $t) }, - error_cb => sub { warn "$_[1]\n" }, - disconnect_cb => sub { warn "Got disconnected... exiting...\n"; $cv->send }, + error_cb => sub { warn "$_[1]\n" if $verbose }, + disconnect_cb => sub { warn "Got disconnected after $t total messages... exiting...\n" if $verbose; $cv->send }, ); $cv->recv; + + +sub usage { + print "Error: @_\n" if @_; + + print <<" EOU"; +Usage: consumer.pl [--help|-h] [--print|-p] topic channel + + Consume messages from channel linked to topic . + Topic and channel parameters are mandatory. + + Options: + + --help or -h Prints this message and exits + --verbose or -v Writes debug information about connections, + disconnections and errors + + --print or -p Prints each received message + EOU + + exit(1); +}