- 引言
- 本书涉及的内容
- 第 1 部分 Python 开发入门
- 第 1 章 Python 入门
- 第 2 章 开发 Web 应用
- 第 3 章 Python 项目的结构与包的创建
- 第 4 章 面向团队开发的工具
- 第 5 章 项目管理与审查
- 第 6 章 用 Mercurial 管理源码
- 第 7 章 完备文档的基础
- 第 8 章 模块分割设计与单元测试
- 第 9 章 Python 封装及其运用
- 第 10 章 用 Jenkins 持续集成
- 第 11 章 环境搭建与部署的自动化
- 第 12 章 应用的性能改善
- 第 13 章 让测试为我们服务
- 第 14 章 轻松使用 Django
- 第 15 章 方便好用的 Python 模块
- 附录 A VirtualBox 的设置
- 附录 B OS(Ubuntu)的设置
文章来源于网络收集而来,版权归原创者所有,如有侵权请及时联系!
12.3 gunicorn 简介
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论