【问题标题】:Is there a way to use package/global variables with Dancer and Starman?有没有办法在 Dancer 和 Starman 中使用包/全局变量?
【发布时间】:2013-11-17 19:49:40
【问题描述】:

当与 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 上问过这个问题。持久变量对我来说似乎很有用,没有它们人们怎么跳舞?

提前感谢您的帮助。

【问题讨论】:

  • 使用轻量级数据库,如 mongodb 或 couchbase 来获取持久值。数据库引擎可以保护您免受同时修改值的问题
  • @user1937198,这不会比将变量存储在内存中慢很多吗?

标签: perl dancer starman


【解决方案1】:

您将需要一个像 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

【讨论】:

    猜你喜欢
    • 2016-05-23
    • 1970-01-01
    • 2017-09-01
    • 1970-01-01
    • 2018-03-07
    • 2019-10-11
    • 2021-10-07
    • 2021-11-12
    • 1970-01-01
    相关资源
    最近更新 更多