Gunicorn独角兽

1. 关于Gunicorn

Gunicorn是一个开源的Python WSGI HTTP服务器,移植于Ruby的Unicorn项目的采用pre-fork模式的服务器。Gunicorn服务器可与各种Web框架,包括django、flask、pyramid等。只要简单配置执行,轻量级的资源消耗,而且相当迅速。与各个Web结合紧密,部署很方便。缺点不支持HTTP 1.1,并发访问性能也不高。

 

关于WSGI:WSGI即Python Web server Gateway Interface,是Python专门的用于Python应用程序或框架与Web服务器之间的一种接口,没有官方的实现,因为WSGI更像一个协议,只要遵照这些协议,WSGI应用都可以在任何服务器上运行,反之亦然。

 

Gunicorn的特征:

  1. 支持WSGI,Django和Paster

  2. 自动化的工作进程管理

  3. 简单的Python配置

  4. 多工作者配置

  5. 多种服务器钩子以便扩展

  6. 兼容Python 2.x >=2.6 或 3.x >=3.2

2. 安装Gunicorn

a. 安装

pip install gunicorn

b. 运行

运行Gunicorn可以通过命令gunicorn或者与Django、Paster结合使用的gunicorn_django、gunicorn_paster来实现

gunicorn:使用该命令来运行一个不需要传输层的WSGI应用,基本语法:

gunicorn [OPTIONS] APP_MODULE

示例代码:

def app(environ, start_response):
    """Simplest possible application object"""
    data = 'Hello, World!\n'
    status = '200 OK'
    response_headers = [
        ('Content-type','text/plain'),
        ('Content-Length', str(len(data)))
    ]
    start_response(status, response_headers)
    return iter([data])

执行命令:

gunicorn --workers=2 test:app

通过浏览器访问http://127.0.0.1:8000显示“Hello, World!”

3. Gunicorn架构

a. 服务器模式

Gunicorn基于pre-fork的工作者模式,即有一个中央master进程来管理一系列的工作进程,master并不知道各个独立客户端。所有的请求和响应完全由工作进程去完成。

master通过一个循环不断监听各个进程的信号并作出相应反应,这些信号包括TTIN、TTOU和CHLD。TTIN和TTOU告诉master增加或者减少正在运行的进程数,CHLD表明一个子进程被终止了,在这种情况下master进程会自动重启这个失败的进程。

b. 进程的同步和异步模式

默认情况下,Gunicorn的工作进程是同步执行的模式,即单个进程在某个时间只处理一个请求。同时,Gunicorn也支持Gevent、Eventlet来实现异步,通过--worker-class选项可以指定工作方式:

gunicorn --worker-class=gevent myapp:app

以下是官方列举的需要异步工作模式的情况:

  • Applications making long blocking calls (Ie, external web services)
  • Serving requests directly to the internet
  • Streaming requests and responses
  • Long polling
  • Web sockets
  • Comet

c. 进程数

Gunicorn只需要4-12个工作进程就能够每秒处理成百上千的请求,所以不需要扩充太多的进程数。

 

参考官方:Gunicorn

 

posted @ 2017-10-19 21:50  luchuangao  阅读(1313)  评论(0编辑  收藏  举报