gunicorn多进程不死_WEB,gunicorn - 无论是多进程、多线程、协程模式,同一个浏览器窗口多个标签页访问同一个url,看上去不会并发的问题...
TL;DR
其實是瀏覽器同一個窗口下限制了對同一個url會執行串行操作。
1.參考
2.現象
我有一個WSGI APP,每次處理request都睡眠5秒。不管多進程、多線程、協程跑WSGI APP,同一個瀏覽器窗口,不同的標簽頁,同一個url,都是串行執行(一個接一個完成,不管gunicorn是多進程、多線程、協程的并發模式)。例如同一個瀏覽器窗口,3個標簽頁,都是花費15秒。
import time
from datetime import datetime
from wsgiref.validate import validator
from gunicorn import __version__
@validator
def app(environ, start_response):
"""Simplest possible application object"""
time_begin = datetime.now()
# time_being = time.time()
data = '{time_begin}{time_end}'
status = '200 OK'
response_headers = [
('Content-type', 'text/plain'),
('Content-Length', str(len(data))),
('X-Gunicorn-Version', __version__),
('Foo', 'B\u00e5r'), # Foo: B?r
]
time.sleep(5) # 關鍵在這。
# time_end = time.time() - time_begin
time_end = datetime.now() - time_begin
data = data.format(time_begin=time_begin, time_end='x')
data = bytes(data, encoding='utf-8')
start_response(status, response_headers)
return iter([data])
無論哪種模式,都是15秒。
gunicorn --workers=1 --threads=3 test1:app -b 0:9999 --log-level debug # 多線程
gunicorn --workers=3 --threads=1 test1:app -b 0:9999 --log-level debug # 多進程
gunicorn --workers=3 --threads=3 test1:app -b 0:9999 --log-level debug # 多進程 + 多線程
gunicorn --workers=1 --threads=1 test1:app -b 0:9999 --log-level debug # 協程
gunicorn --workers=3 --threads=3 test1:app -b 0:9999 --log-level debug -k gevent # 多進程 + 多線程 + 協程
3.疑問
這看上去不就不能并發嘛?說好的多進程、多線程、協程、Non-blocking I/O的并發模式呢?
4.本質
通過第一點“參考”,可以看出,這其實是瀏覽器的鍋。瀏覽器同一個窗口(有不同標簽頁)對同一個url會串行化訪問;其實瀏覽器還有另外一個限制(對同一個域名的資源有并發限制),這是另外一個問題了。
5.解決辦法
方法一,瀏覽器同一個窗口,不同標簽頁,給同一個url加上一些冗余的query params就行了。例如,同一個窗口不同標簽頁同時訪問一下三個url,返回的請求時間差不多在同一時間完成。
http://127.0.0.1:9999/?a=1
http://127.0.0.1:9999/?a=2
http://127.0.0.1:9999/?a=3
方法二,在瀏覽器不同窗口,或者不同瀏覽器訪問同一個url,也可以“并發”。這是非常合理的。因為這繞過了瀏覽器的限制,而且代表了不同的client的request。
6.總結
其實這個看上去是問題的問題不是問題,因為線上真正的請求一般不會出現這些情況。因為線上的請求是來自不同的瀏覽器、不同的curl,或者說,不同的http client,那就沒有瀏覽器這個小小的限制啦!
與50位技術專家面對面20年技術見證,附贈技術全景圖總結
以上是生活随笔為你收集整理的gunicorn多进程不死_WEB,gunicorn - 无论是多进程、多线程、协程模式,同一个浏览器窗口多个标签页访问同一个url,看上去不会并发的问题...的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: cbow word2vec 损失_wor
- 下一篇: Html制作知识库管理系统,HTML 编