ojolicious中的Globals和Threads用于处理不

ojolicious中的Globals和Threads用于处理不

本文介绍了Mojolicious中的Globals和Threads用于处理不同的路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In my Mojolicious perl code I handle a jobs created and watched from a remote client.

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

I keep the jobs in a array of hashes, which is a global variable.

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

It is then used in handlers of PUT '/job/create' and GET '/job/status'.When adding a new job with the PUT '/job/create' the array getsextended in the subroutine (it contains 4 elements in the code below),but when requesting the jobs' status via GET '/job/status' the list ofjobs, the array does not contain the added elements (it counts 2elements).

谢谢Jan

这是代码:

#!/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();

推荐答案

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

This won't really work, as hypnotoad is using fork, not threads. I suggest storing data in something like a database or Cache::FastMmap.

这篇关于Mojolicious中的Globals和Threads用于处理不同的路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-07 00:12