利用nginx + fastcgi实现图片识别服务器

2019-10-17 16:58:49王旭

为什么说是减少了互动的开销呢?这就要看两种处理方式的区别!

cgi的工作流程:

每当客户端发出一个新的请求,首先要创建一个cgi子进程,然后cgi处理完请求,有多少个连接就会有多少个cgi子进程启动,当请求量大的时候会占用大量的系统资源。

fastcgi

fastcgi 是使用持续的进程处理一连串的请求,这些进程有fastcgi的进程管理器来进行管理具体流程如下所示:

也可以这样比喻:

cgi在卖鸡蛋灌饼,等到顾客要吃的时候,他开始点火,打鸡蛋,摊饼,然后熄火。然后等待下一个顾客

fastcgi就是早餐店老版,雇佣了一帮服务员,专门做需要现场做的饭,老板只需要把订单安排下去,服务员负责盛粥煎饼。

具体步骤

搭建c++的开发环境 搭建nginx 安装fastcgi 安装fastcgi的进程管理器spawn-cgi 编写运行程序 编译运行

工欲善其事,必先利其器,首先搭建环境把!

通过阅读不少的博客内容找到了最简单的安装步骤,好多都是通过下载源代码,然后通过make进行编译,不过对于这些比较常用的库,软件包中已经集成了。

C++开发环境安装

apt-get install build-essential

nginx

apt-get install nginx

fastcgi

sudo apt-get install libfcgi-dev

spawn-fcgi

apt-get install spawn-fcgi

编写运行程序

#include <iostream>
#include "fcgio.h"
 
using namespace std;
 
int main(void) {
 // Backup the stdio streambufs
 streambuf * cin_streambuf = cin.rdbuf();
 streambuf * cout_streambuf = cout.rdbuf();
 streambuf * cerr_streambuf = cerr.rdbuf();
 
 FCGX_Request request;
 
 FCGX_Init();
 FCGX_InitRequest(&request, 0, 0);
 
 while (FCGX_Accept_r(&request) == 0) {
  fcgi_streambuf cin_fcgi_streambuf(request.in);
  fcgi_streambuf cout_fcgi_streambuf(request.out);
  fcgi_streambuf cerr_fcgi_streambuf(request.err);
 
  cin.rdbuf(&cin_fcgi_streambuf);
  cout.rdbuf(&cout_fcgi_streambuf);
  cerr.rdbuf(&cerr_fcgi_streambuf);
 
  cout << "Content-type: text/htmlrn"
    << "rn"
    << "<html>n"
    << " <head>n"
    << " <title>Hello, World!</title>n"
    << " </head>n"
    << " <body>n"
    << " <h1>Hello, World!</h1>n"
    << " </body>n"
    << "</html>n";
 
 }
 cin.rdbuf(cin_streambuf);
 cout.rdbuf(cout_streambuf);
 cerr.rdbuf(cerr_streambuf);
 return 0;