太多的sse连接挂起了网页

Cal*_*lum 5 python django server-sent-events gunicorn

是什么限制了SSE(服务器发送事件)连接的数量?

我一直在使用django/gunicorn/django-sse开展一个项目.

当我限制页面的sse连接数量时,我的项目很有效(5个工作6个挂起),这不是一个很大的问题,因为我使用分页因此可以限制每页的数量.但我希望能够拥有我喜欢的数量.

我的问题是:连接的数量是减慢速度,还是传输的数据量?

第一个问题,我认为我可以通过让他们共享一个连接来解决,但第二个问题可能会限制我更多.

它可能是什么想法?

编辑:

客户端JS SSE代码:

function event(url, resource_name, yes, no, audio_in, audio_out, current_draw){
    /**
     * Listens for events posted by the server
     * 
     * Useful site for understanding Server Sent Events:
     *    http://www.w3.org/TR/eventsource/
     */
    var source = new EventSource(url);
    source.addEventListener("message", function(e) {
        resetTime(resource_name);
        data = updateStatus(e.data, yes, no, audio_in, audio_out, current_draw);
        document.getElementById(resource_name+"-in").src = data.audio_in_src
        document.getElementById(resource_name+"-in").alt = data.audio_in_alt
        document.getElementById(resource_name+"-out").src = data.audio_out_src
        document.getElementById(resource_name+"-out").alt = data.audio_out_alt
        document.getElementById(resource_name+"-current").innerHTML = data.current_draw + " A"
    });
}
Run Code Online (Sandbox Code Playgroud)

在views.py中

class ServerSentEvent(RedisQueueView):

    def get_redis_channel(self):
        """
        Overrides the RedisQueueView method to select the channel to listen to
        """
        return self.kwargs["resource_name"]
Run Code Online (Sandbox Code Playgroud)

在urls.py中

urlpatterns = patterns('',
                       url(r'^$',
                           views.Resources_page.as_view(),
                           name='resources_page'),
                       url(r'^(?P<resource_name>\w+)/$',
                           views.StatusPage.as_view(),
                           name='status_page'),
                       url(r'^(?P<resource_name>\w+)/sse/$',
                           views.ServerSentEvent.as_view(),
                           name='sse'),)
Run Code Online (Sandbox Code Playgroud)

Don*_*ing 0

如果您使用syncgunicorn的工作进程(默认),那么您的服务器的并发连接数只能与工作进程的数量一样多。

工作sync线程是为 CPU 密集型任务而设计的,因此建议使用2N + 1工作线程(其中 N 是可用核心的数量)。如果您的 SSE 端点在逻辑上与此等效...

while True:
    msg = "foo"
    yield msg
    sleep(1)
Run Code Online (Sandbox Code Playgroud)

...然后您就有了 I/O 绑定视图。无论您在该代码块上投入多少 CPU 时间,它都被设计为永远不会结束。如果您使用该django_sse项目,那么这几乎正是您的 SSE 视图所做的事情

解决方案是为gunicorn 使用异步工作线程类。安装gevent并将--worker-class=gevent选项传递给gunicorn,您就踏上了通往异步乌托邦的道路。