1

多年来,我一直在使用 stomp.py 和 stompest 与 activemq 进行通信,效果很好,但这主要是使用独立的 python 守护进程。

我想使用来自网络服务器的这两个库与后端进行通信,但我很难找到如何做到这一点,而无需为每个请求创建新连接。

是否有安全处理网络服务器中 TCP 连接的标准方法?在其他语言中,该级别的某种全局对象将用于连接池。

4

1 回答 1

0

HTTP 是一种同步协议。每个等待的客户端在等待响应时都会消耗服务器资源(CPU、内存、文件描述符)。这意味着 Web 服务器必须快速响应。HTTP Web 服务器在响应请求时不应阻塞外部长时间运行的进程。

解决方案是异步处理请求。有两个主要选项:

  1. 使用轮询。

    POST将新任务推送到消息队列:

    POST /api/generate_report
    {
         "report_id": 1337
    }
    

    GET检查 MQ(或数据库)的结果:

    GET /api/report?id=1337
    {
        "ready": false
    }
    
    GET /api/report?id=1337
    {
        "ready": true,
        "report": "Lorem ipsum..."
    }
    

    Django 生态系统中的异步任务通常使用Celery实现,但您可以直接使用任何 MQ。

  2. 使用 WebSocket。

有用的网址:

  1. 什么是长轮询、Websocket、服务器发送事件 (SSE) 和 Comet?
  2. https://en.wikipedia.org/wiki/Push_technology
  3. https://www.reddit.com/r/django/comments/4kcitl/help_in_design_for_long_running_requests/
  4. https://realpython.com/asynchronous-tasks-with-django-and-celery/
  5. https://blog.heroku.com/in_deep_with_django_channels_the_future_of_real_time_apps_in_django

编辑:

下面是一个伪代码示例,说明如何重用与 MQ 的连接:

projectName/appName/services.py

import stomp

def create_connection():
    conn = stomp.Connection([('localhost', 9998)])
    conn.start()
    conn.connect(wait=True)
    return conn

print('This code will be executed only once per thread')
activemq = create_connection()

projectName/appName/views.py

from django.http import HttpResponse
from .services import activemq

def index(request):
    activemq.send(message='foo', destination='bar')
    return HttpResponse('Success!')
于 2018-05-26T14:39:05.253 回答