返回介绍

12.3 gunicorn 简介

发布于 2024-01-21 17:11:03 字数 2877 浏览 0 评论 0 收藏 0

gunicorn 是面向 Python WSGI 应用的 HTTP 服务器。它在 Linux/Unix 上运行,优点是轻量级且速度快。gunicorn 通过一个控制进程和多个工作进程来执行应用程序。由于它是一个 Python 模块,所以可以变更工作进程的类以及扩展服务器本身。

12.3.1 安装 gunicorn

gunicorn 可以用 pip 命令安装(LIST 12.5)。

LIST 12.5 用 pip 命令安装

$ pip install gunicorn

通过上述方法安装 gunicorn 后,就可以使用 gunicorn 命令了。

12.3.2 在 gunicorn 上运行应用

首先设置一个工作进程,运行应用(LIST 12.6)。

LIST 12.6 用 gunicorn 命令运行留言板应用

$ gunicorn -w 1 -b 127.0.0.1:8000 guestbook

我们在这个状态下再执行一次 ab 命令,检测结果如下。

Server Software:    gunicorn/19.1.1
Server Hostname:    127.0.0.1
Server Port:      8000
Document Path:      /
Document Length:    7398 bytes
Concurrency Level:    100
Time taken for tests:   4.469 seconds
Complete requests:    1000
Failed requests:    0
Write errors:       0
Total transferred:    7560000 bytes
HTML transferred:     7398000 bytes
Requests per second:  223.75 [#/sec] (mean)
Time per request:     446.937 [ms] (mean)
Time per request:     4.469 [ms] (mean, across all concurrent requests)
Transfer rate:      1651.87 [Kbytes/sec] received
Connection Times (ms)
        min  mean[+/-sd] median   max
Connect:    0  1   2.2    0     8
Processing:  31  424  71.7  444   462
Waiting:     14  424  71.8  443   462
Total:     37  425  69.8  444   469
Percentage of the requests served within a certain time (ms)
  50%  444
  66%  444
  75%  444
  80%  444
  90%  445
  95%  445
  98%  446
  99%  446
 100%  469 (longest request)

可以看到与之前用 Flask 内置服务器时的结果差别不大。

由于当前运行应用的虚拟机的 CPU 数设置为 2,因此单独一个工作进程无法充分利用 CPU 资源。所以进程数应至少设置为 2。

于是我们将 gunicorn 的工作进程设置为 2,再次执行 ab 命令进行检测。工作进程数用 -w 选项指定(LIST 12.7)。

LIST 12.7 用 gunicorn 命令运行应用(工作进程数为 2)

$ gunicorn -w 2 -b 127.0.0.1:8000 guestbook

检测结果如下。

Server Software:    gunicorn/19.1.1
Server Hostname:    127.0.0.1
Server Port:      8000
Document Path:      /
Document Length:    7398 bytes
Concurrency Level:    100
Time taken for tests:   2.376 seconds
Complete requests:    1000
Failed requests:    0
Write errors:       0
Total transferred:    7560000 bytes
HTML transferred:     7398000 bytes
Requests per second:  420.91 [#/sec] (mean)
Time per request:     237.582 [ms] (mean)
Time per request:     2.376 [ms] (mean, across all concurrent requests)
Transfer rate:      3107.48 [Kbytes/sec] received
Connection Times (ms)
        min  mean[+/-sd] median   max
Connect:    0  1   1.6    0     7
Processing:  18  225  37.3  235   248
Waiting:     17  225  37.3  235   247
Total:     25  226  35.8  235   252
Percentage of the requests served within a certain time (ms)
  50%  235
  66%  236
  75%  236
  80%  236
  90%  236
  95%  237
  98%  238
  99%  238
 100%  252 (longest request)

平均响应时间缩短了 40%,可见速度快了许多。接下来我们再看看用作 Web 服务器和代理服务器的 nginx。

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文