首先,我是Perl和Mojo的新手,所以我会尽我最大的努力。:D
问题是,I需要并行工作,因此该服务需要每秒钟处理几次调用,该服务将允许其他服务通过REST连接,以便下载和处理文件。我正在对这个想法做一些测试,但没有成功。
我一直在Mojo::IOLoop上进行测试,但是我想我误解了这方面的一些概念,因为每个使用循环和计时器的实现都是绝对错误的。
实际上我的工作流程是这样的:
(1)呼叫REST
(2)核实在mongodb上提供的网址
(3)下载文件associed到该mongo对象。
所以实际上这是可行的,但我不知道如何实现它来并行工作.
#!/usr/bin/env_perl
use Mojolicious::Lite;
use MongoDB;
my $mongo = MongoDB::MongoClient->new(host => 'xxxx.mongohq.com',port => 'xxxxx', username => 'xxxxx', password => 'xxxxx', db_name => 'xxxxx');
my $database = $mongo->get_database( 'xxxxx' );
my $collection = $database->get_collection( 'xxxxx' );
any [qw/ get post /] => '/:action/:objid' => sub {
my $self = shift;
#Parsing objectid...
my $objectid = $self->param('objid');
my $id = MongoDB::OID->new(value => $objectid);
my $all = $collection->find({_id => $id});
my $dts = $all->next;
download($dts->{parsedoc}->{url},"final_name.xml");
};
app->start;
sub download {
say "Starting new download..";
my $ua = Mojo::UserAgent->new(max_redirects => 5);
my $tx = $ua->get($_[0]);
$tx->res->content->asset->move_to($_[1]);
say "Download ends.";
}在这里实现IOLoop的最佳方法是哪一种?我已经使用了一些魔术计时器的例子,但也许我需要重新排序我的应用程序流?提前谢谢。
发布于 2013-07-02 01:43:19
正如我在评论中提到的,Mojo::IOLoop与并行性无关,而与事件循环有关。这意味着可能需要很长时间的操作可能会启动,然后只继续一次完成,而不会阻塞其他进程。在您的示例中,对Mongo的调用和下载都是这些类型的长时间运行的进程,您可能希望将它们放入事件循环中。当与回调一起使用时,UserAgent是非阻塞的(操作完成后调用的动作)。要对Mongo做同样的事情,你需要确保你的蒙古库可以以一种非阻塞的方式被使用。
我模拟了一个小例子,它忽略了Mongo部分(读者练习),并以非阻塞的方式使用UserAgent。
#!/usr/bin/env perl
use Mojolicious::Lite;
helper download => sub {
my ($c, $url, $target) = @_;
my $ua = $c->app->ua->max_redirects(5);
say "Starting new download ($url) ...";
$ua->get( $url, sub {
my ($ua, $tx) = @_;
say "Finished download ($url) ...";
$tx->res->content->asset->move_to($target);
say "File saved ($url --> $target)";
$c->render( text => "File saved ($url --> $target)" );
});
};
any [qw/ get post /] => '/:action/:objid' => sub {
my $self = shift;
$self->render_later; # prevent auto-render
#Parsing objectid
my $objectid = $self->param('objid');
#verify url here ...
# example url
my $url = 'http://www.google.com';
$self->download($url,"final_name.xml");
};
app->start;https://stackoverflow.com/questions/17403775
复制相似问题