【问题标题】:Globals and Threads in Mojolicious for handling different pathsMojolicious 中用于处理不同路径的全局变量和线程
【发布时间】:2012-03-13 17:11:37
【问题描述】:

在我的 Mojolicious perl 代码中,我处理从远程客户端创建和监视的作业。

我将作业保存在一个哈希数组中,这是一个全局变量。

然后在 PUT '/job/create' 和 GET '/job/status' 的处理程序中使用它。 当使用 PUT '/job/create' 添加新作业时,数组会得到 在子程序中扩展(它在下面的代码中包含 4 个元素), 但是当通过 GET '/job/status' 请求工作的状态时, 作业,该数组不包含添加的元素(它计数 2 元素)。

谢谢,简

代码如下:

#!/usr/bin/perl -w

use threads; 
use threads::shared; 
use Mojolicious::Lite; 
use Mojo::JSON; 
my (%record, %job1, %job2, %job3, @jobs) : shared; 

%job1 = ( id=>"id1"); 
%job2 = ( id=>"id2"); 
%job3 = ( id=>"id3"); 

push ( @jobs, \%job1 ); 
push ( @jobs, \%job2 ); 

app->config(hypnotoad => {listen => ['http://*:3000']}); 

put '/job/create' => sub { 
    my $self = shift; 
    my $obj = Mojo::JSON->decode( $self->req->body ); 
    my $id = $obj->{id}; 
    %record = (id => $id); 
    push ( @jobs, \%record ); # test the global prefilled 
    push ( @jobs, \%job3 );   # test the global locally filled 
    $self->render(text => "Created job id $id. Jobs count: " . 
$#jobs ); 
}; 

get '/job/status' => sub { 
    my $self = shift; 
    my $out = "["; 
    for(my $i=0; $i<$#jobs+1; $i++) { 
        $out .= "{id:\""  . $jobs[$i]{id}      . "\","; 
        $out .= "," if $i<$#jobs; 
    } 
    $out .= "]"; 
    $self->render(text => "allJobsInfo($out). Num jobs: " . $#jobs); 
};

app->start();

【问题讨论】:

    标签: perl variables global shared mojolicious


    【解决方案1】:

    这不会真正起作用,因为hypnotoad 使用的是 fork,而不是线程。我建议将数据存储在数据库或 Cache::FastMmap 之类的东西中。

    【讨论】:

    • 感谢您的帮助。最后,我转向使用 CouchDB 的解决方案。顺便说一句,看起来很不错。 :)
    • 替代perl your.app daemon -l 'http://*:3000' 也可以工作。 see Built-in web server
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-20
    • 1970-01-01
    • 1970-01-01
    • 2023-03-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多