Perl使用nginx FastCGI环境做WEB开发实例
HelloWorld
一个简单的helloworld例子:
#!/usr/bin/envperl usestrict; usewarnings; useCGI::Fast; while(my$q=newCGI::Fast) { print$q->header("text/plain"); print"HelloWorld"; }
和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来启动前面的HelloWorld:
$spawn-fcgi-n-a127.0.0.1-p8184-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"SIGINTSIGTERM whiletrue do #首次启动或者文件改动后都需要关闭之前的进程 term #以nofork方式启动脚本来调试,并将PID写入到文件 spawn-fcgi-n-a127.0.0.1-p8184-f./$MAIN & pid=$! echo$pid>$PID_FILE echo"MyPerlservicestarted,pid=$pid" #监控文件变化 files=`find.-name'*.pl'-o-name'*.pm'-o-name'*.html'` md5=`md5sum$files|md5sum` #waitforfilechange while[[`md5sum$files|md5sum`="$md5"]] do sleep1 done echo"Filechangesdetected,restartingservice" done