当前位置: 移动技术网 > IT编程>网页制作>Perl > Perl使用nginx FastCGI环境做WEB开发实例

Perl使用nginx FastCGI环境做WEB开发实例

2017年12月08日  | 移动技术网IT编程  | 我要评论

hello world

一个简单的hello world例子:

复制代码 代码如下:

#!/usr/bin/env perl
use strict;
use warnings;
use cgi::fast;
while(my $q = new cgi::fast)
{
 print $q->header("text/plain");
 print "hello world";
}

和cgi的区别仅在于多了一个循环来接受请求,cgi::fast对象和cgi接口是一样的,而且该脚本也可以当做cgi脚本使用。

搭建nginx + fastcgi 环境

perl使用cgi::fast包来提供fastcgi服务,该包提供两种方式来启动fastcgi进程,一个是直接使用该包提供的服务将当前进程变为fastcgi进程,另外一个是使用第三方工具spawn-fcgi来启动。
nginx配置方式例子:

复制代码 代码如下:

        location / {
            fastcgi_pass   127.0.0.1:8184;
            fastcgi_param  script_filename  /scripts$fastcgi_script_name;
            include        fastcgi_params;
        }

配置好nginx后,使用spawn-fcgi来启动前面的hello world:
复制代码 代码如下:

$ spawn-fcgi -n -a 127.0.0.1 -p 8184 -f ./main.pl


调试支持

在前面的命令行里使用了参数-n,让spawn-fcgi不要fork出多个进程,并阻塞,允许用户ctrl+c来关闭,产品服务器可以去掉这个参数来充分利用服务器的多核来提供更高的并发数。我之前写了一个bash脚本,允许在文件改动的情况下重启服务,方便调试perl程序,代码如下:

复制代码 代码如下:

#!/bin/bash
#pid文件和需要启动的脚本
pid_file=service.pid
main=main.pl

#关闭之前启动的进程
term() {
    test -e $pid_file || return
    pid=`cat $pid_file`
    kill -s -0 $pid  || return
    echo "terminating $main $pid"
    rm -f $pid_file
    kill $pid
    wait $pid
}
#当前脚本退出的时候也关闭启动了的fastcgi进程
trap "term;exit" sigint sigterm
while true
do
#首次启动或者文件改动后都需要关闭之前的进程
    term
#以no fork方式启动脚本来调试,并将pid写入到文件
    spawn-fcgi -n -a 127.0.0.1 -p 8184 -f ./$main  &
    pid=$!
    echo $pid > $pid_file
    echo "my perl service started, pid = $pid"
#监控文件变化
    files=`find . -name '*.pl' -o -name '*.pm' -o -name '*.html'`
    md5=`md5sum $files|md5sum`
#wait for file change
    while [[ `md5sum $files|md5sum` = "$md5" ]]
    do
        sleep 1
    done
    echo "file changes detected, restarting service"
done


该脚本已在mac osx和linux下测试通过

路由系统

做web开发离不开路由实现,来对不同请求来做出特定的响应。
路由请求依赖http method和uri两部分,因此主要就是需要这两者来做分派。
在cgi中可以通过环境变量request_method和request_uri来获取请求方法和uri。
因此一个简单的路由系统实际上可以分解为一个二级的map,注册路由实际上就是往这个map里放入规则对应的处理函数,而分派请求则是从这个map里根据规则获取对应的处理函数,一个简单的例子:

复制代码 代码如下:

my %routers = ();

sub not_found
{
    print "status: 404\n";
    print "content-type: text/html\n\n";
    print<<eof
<html>
<body>
<h1>404 not found</h1>
cannot find $env{request_path}.
</body>
</html>
eof
}


sub add_rule
{
    my ($method, $path, $callback) = @_;
    my $handlers = $routers{$method};
    $handlers = $routers{$method} = {} if not $handlers;
    $handlers->{$path} = $callback;
}

sub dispatch
{
    my $q = shift;
    my $method = $env{request_method};
    my $uri = $env{request_uri};
    $uri =~ s/\?.*$//;
    my $handler = ($routers{$method} || {})->{$uri} || not_found;
    eval
    {
 &$handler($q);
    };
    print stderr "failed to handle $method $uri: $@\n" if $@;
}


使用这个路由系统的例子:
复制代码 代码如下:

sub index
{
    my ($q) = @_;
    print $q->header('text/plain');
    print "hello world!";
}

router::add_rule('get', '/', \&index);


模板系统

perl提供了大量的模板系统的实现,我个人最喜欢的是template toolkit,文档也非常丰富,网站是 http://www.template-toolkit.org/ 。

将前面的index修改为使用模板的例子:

复制代码 代码如下:

use template;

my $tt = new template({include_path => 'templates', interpolate => 1});

sub index
{
    my ($q) = @_;
    my $output = '';
    print $q->header('text/html');

    $tt->process('', {world => 'world'}, $output) || die $tt->error();
    print $output;
}


其中templates/文件内容如下:
复制代码 代码如下:

<html>
<head><title>demo</title></head>
<body>
hello ${world}
</body>
</html>

完!

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网