Permalink
Browse files

Create a consumer that tracks the number of pending HTTP reqeusts.

It's not ideal since POE::Component::Client::HTTP can be overloaded.
A more complete consumer would throttle the requests so too many
couldn't be started at once.
  • Loading branch information...
1 parent 4797a72 commit 3fe11a868d8e19007be6474e1a5604d316b03379 @rcaputo committed Sep 27, 2012
Showing with 70 additions and 0 deletions.
  1. +3 −0 eg/HttpResponseEvent.pm
  2. +67 −0 eg/eg-22-multiple-http-requests.pl
View
@@ -18,4 +18,7 @@ has response => (
required => 1,
);
+__PACKAGE__->make_event_cloner;
+__PACKAGE__->meta->make_immutable;
+
1;
@@ -0,0 +1,67 @@
+#!/usr/bin/env perl
+# vim: ts=2 sw=2 noexpandtab
+
+use warnings;
+use strict;
+use lib qw(../lib);
+
+{
+ package ConcurrentHttpClient;
+ use Moose;
+ extends 'Reflex::Base';
+
+ use HttpClient;
+ use Reflex::Trait::Watched qw(watches);
+
+ watches http_client => (
+ is => 'ro',
+ isa => 'HttpClient',
+ default => sub { HttpClient->new() },
+ );
+
+ has pending => (
+ is => 'rw',
+ isa => 'Int',
+ default => 0,
+ );
+
+ sub requests {
+ my ($self, @http_requests) = @_;
+
+ foreach my $request (@http_requests) {
+ $self->http_client()->request( $request );
+ }
+
+ $self->pending( $self->pending() + @http_requests );
+ }
+
+ sub on_http_client_response {
+ my ($self, $response) = @_;
+ $self->re_emit( $response, -name => 'response' );
+
+ return if $self->pending( $self->pending() - 1 );
+
+ $self->emit( -name => "empty" );
+ };
+}
+
+### Main usage.
+
+use HTTP::Request;
+
+my $client = ConcurrentHttpClient->new();
+$client->requests(
+ map { HTTP::Request->new( GET => $_ ) }
+ 'http://poe.perl.org',
+ 'http://duckduckgo.com/',
+ 'http://metacpan.org/',
+ 'http://perl.org/',
+ 'http://twitter.com/',
+);
+
+while (my $event = $client->next()) {
+ last if $event->_name() eq 'empty';
+ print $event->response()->code(), " = ", $event->request()->uri(), "\n";
+}
+
+exit;

0 comments on commit 3fe11a8

Please sign in to comment.