Nginx的perl模块开发

因为公司业务需要记录每一个用户某一个类型的文件最后一次请求,提供继续阅读功能,所以在Nginx里加了一个小模块,当有用户请求进来时,响应数据并在Memcached和Mongodb记录此URL。

配置Nginx

引用

perl_modulesperl/lib;

perl_requirebookvisit.pm;

引用

location~*^.+\.bcs$

{

perlbookvisit::handler;

root/byread/books/vipbook;

}

package bookvisit;
use warnings;
use nginx;
use DBI;
use POSIX qw/strftime/;
use MongoDB;
use Cache::Memcached;

my $connection = MongoDB::Connection->new(host => 'localhost', port => 27017);
my $database   = $connection->get_database('bookvisit');
my $visitlog = $database->get_collection('visitlog');
my $lastpage = $database->get_collection('lastpage');

my $memd = new Cache::Memcached {
	'servers' => ["192.168.0.139:11211"],
	'debug' => 0,
	'compress_threshold' => 10_000,
};

sub handler {
	my $r = shift;
	return OK if $r->header_only;
	if (! -f $r->filename) {
		return DECLINED;
	}
	else
	{
		$r->header_out('Content-Type','text/html; charset=utf-8');
		$r->send_http_header;
		@s=stat($r->filename);
		$r->header_out('Content-Length',$s[7]);
		$r->header_out('Length',$s[7]);
		$r->sendfile($r->filename);
		$r->rflush;

		$uri = $r->uri;
		$args = $r->args;

		if( $uri =~ /\/(\w+)\/(\d+).(bcs|txt)/ )
		{
			$bookid = $1;
			$isvip = "0";
			$page = 'http://192.168.0.137'.$uri;
		}
		if( $uri =~ /\/(\d+)\/(f|r)\/(\d+).(bcs|txt)/ )
		{
			$bookid = $1;
			$isvip = "1";
			$page = 'http://192.168.0.138'.$uri;
		}
		if( $args =~ /byid=(\d+)/ )
		{
			$byid = $1;
		}
		$visitime = strftime("%Y-%m-%d %H:%M:%S", localtime time);
		&lastpage;
		&meminsertpage;
		return OK;
	}
}

sub lastpage {
	$lastpage->update({'byid' => $byid},{'$set' => {page => $page,visitime => $visitime} },{"upsert" => 1});
	return OK;
}

sub meminsertpage {
	$memd->set("_book_lastest_read_$byid",$page);
	return OK;
}

1;
__END__

相关推荐