与Starman一起运行时,我无法找出在Dancer应用程序中使用包变量(或任何种类)的方法。我想这与Starman的预分叉有某种联系,但这应该是功能,而不是错误。

这是示例Dancer应用程序:

package nafig;
use Dancer;

my $a = 0;
$b = 0;
$nafig::c = 0;

any '/' => sub {
    warn join " ", $a++, $b++, $nafig::c++;
};

start;


然后,我连续3次致电该应用。首先,我使用plack参考服务器运行它,并且一切正常。

$ plackup app.pl
HTTP::Server::PSGI: Accepting connections at http://0:5000/
0 0 0 at ... blah-blah-blah
1 1 1 at ... blah-blah-blah
2 2 2 at ... blah-blah-blah


但是当我与Starman做同样的事情时,我得到了以下内容。

$ plackup -s Starman app.pl
2013/11/17-23:33:35 Starman::Server (type Net::Server::PreFork) starting! pid(527)
Resolved [*]:5000 to [::]:5000, IPv6
Not including resolved host [0.0.0.0] IPv4 because it will be handled by [::] IPv6
Binding to TCP port 5000 on host :: with IPv6
Setting gid to "1000 1000 20 24 25 29 30 44 46 108 109 115 121 1000"
Starman: Accepting connections at http://*:5000/
0 0 0 at ... blah-blah-blah
0 0 0 at ... blah-blah-blah
0 0 0 at ... blah-blah-blah


但是,当快速刷新页面时,有时值会按预期增加。我猜,在这些情况下,Starman仍然处于同一分支。

我很惊讶以前从未在stackoverflow上问过这个问题。持久变量对我来说似乎很有用,如果没有它们,人们如何跳舞?

在此先感谢您的帮助。

最佳答案

您将需要一个类似Cache::Memcached的模块,该模块允许您在分支线程上存储状态。

像这样(未经测试)

use strict;
use warnings;

package nafig; #this should start with a capital letter
use Dancer;
use Cache::Memcached;

my $cache =  new Cache::Memcached {
    'servers' => ['127.0.0.1:11211'],
    'compress_threshold' => 10_000,
};

$cache->set("var1", 0);

any '/' => sub {

    my $value = $cache->get("var1");

    warn join " ", $value++;

    $cache->set("var1", $value);
};

start;


从这里改编http://perl.postbit.com/how-to-use-memcached-with-perl.html

10-05 17:39