WEB,gunicorn - 无论是多进程、多线程、协程模式,同一个浏览器窗口多个标签页访问同一个url,看上去不会并发的问题

TL;DR

其实是浏览器同一个窗口下限制了对同一个url会执行串行操作。

1.参考

  1. https://stackoverflow.com/questions/35051499/how-to-get-flask-gunicorn-to-handle-concurrent-requests-for-the-same-route/35051795
  2. https://stackoverflow.com/questions/14864994/gunicorn-doesnt-process-simultaneous-requests-concurrently
  3. https://stackoverflow.com/questions/23038678/requests-not-being-distributed-across-gunicorn-workers

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,那就没有浏览器这个小小的限制啦!

posted @ 2020-10-01 22:58  Rocin  阅读(666)  评论(0编辑  收藏  举报