我正在开发一个基于简单Mojolicious::Lite
的服务器,其中包括一个 websocket 端点。
我想处理一些终止信号以优雅地终止 websocket 连接并避免客户端(java 应用程序)中的异常。
我试图定义我的信号处理程序,就像我以前的服务器使用HTTP::Daemon
. 问题是它们似乎被忽略了。也许在 Mojolicious 层中重新定义了,我还没有找到任何关于它的参考。
我期待看到我的终止消息,但它没有发生
[Mon Mar 23 14:01:28 2020] [info] Listening at "http://*:3000"
Server available at http://127.0.0.1:3000
^C # <-- i want to see my signal received message here if type Ctrl-c
当服务器在终端中处于前台时,我SIGINT
通过输入直接发送Ctrl-C
,并且我可以优雅地终止服务器(例如,当由 cron 或其他无显示方式启动时)带有kill <pid>
.
在以前的一些服务器中,我试图通过处理来非常详尽:
HUP
现在用来重新加载配置的劫持信号SIGINT
Ctrl-CSIGQUIT
Ctrl-\SIGABRT
例如异常库终止SIGTERM
外部终止请求 - “友好”kill
(通过野蛮的反对kill -9
TSTP
使用 Ctrl-Z 暂停CONT
从 Ctrl-Z 恢复时使用fg
orbg
所有这些处理程序都允许在清理资源的情况下优雅地退出,确保数据一致性或在外部更改后重新加载配置或数据模型,具体取决于程序和需求。
我找到了Mojo::IOLoop::Signal
“非阻塞信号处理程序”包,但它似乎是另一回事。错误的?
这是我的简化代码(使用 simple 运行perl ws_store_test.pl daemon
):
文件 ws_store_test.pl
# Automatically enables "strict", "warnings", "utf8" and Perl 5.10 features
use Mojolicious::Lite;
my $store = {};
my $ws_clients = {};
sub terminate_clients {
for my $peer (keys %$ws_clients){
$ws_clients->{$peer}->finish;
}
}
$SIG{INT} = sub {
say "SIGINT"; # to be sure to display something
app->log->info("SIGINT / CTRL-C received. Leaving...");
terminate_clients;
};
$SIG{TERM} = sub {
say "SIGTERM"; # to be sure to display something
app->log->info("SIGTERM - External termination request. Leaving...");
terminate_clients;
};
# this simulates a change on datamodel and notifies the clients
sub update_store {
my $t = localtime time;
$store->{last_time} = $t;
for my $peer (keys %$ws_clients){
app->log->debug(sprintf 'notify %s', $peer);
$ws_clients->{$peer}->send({ json => $store
});
}
}
# Route with placeholder - to test datamodel contents
get '/:foo' => sub {
my $c = shift;
my $foo = $c->param('foo');
$store->{$foo}++;
$c->render(text => "Hello from $foo." . (scalar keys %$store ? " already received " . join ', ', sort keys %$store : "") );
};
# websocket service with optional parameter
websocket '/ws/tickets/*id' => { id => undef } => sub {
my $ws = shift;
my $id = $ws->param('id');
my $peer = sprintf '%s', $ws->tx;
app->log->debug(sprintf 'Client connected: %s, id=%s', $peer, $id);
$ws_clients->{$peer} = $ws->tx;
$store->{$id} = {};
$ws->on( message => sub {
my ($c, $message) = @_;
app->log->debug(sprintf 'WS received %s from a client', $message);
});
$ws->on( finish => sub {
my ($c, $code, $reason) = @_;
app->log->debug(sprintf 'WS client disconnected: %s - %d - %s', $peer, $code, $reason);
delete $ws_clients->{$peer};
});
};
plugin Cron => ( '* * * * *' => \&update_store );
# Start the Mojolicious command system
app->start;