【问题标题】:Batching and queueing in a real-time webserver在实时网络服务器中进行批处理和排队
【发布时间】:2015-11-12 22:15:08
【问题描述】:

我需要一个网络服务器,它通过每 0.5 秒或当它有 50 个 http 请求时(以较早发生的情况为准)将传入请求路由到后端工作人员。在 python/tornado 或任何其他语言中实现它的好方法是什么?

我的想法是将传入的请求发布到 rabbitMQ 队列,然后以某种方式将它们批处理在一起,然后再发送到后端服务器。我想不通的是如何从 rabbitMq 队列中选择多个请求。有人可以指出我正确的方向或建议一些替代方法吗?

【问题讨论】:

  • 您能否提供更多有关您为什么要这样做(批量请求聚集)以及可能的用例的背景信息?
  • 后端服务器是 GPU。因此,并行处理比顺序处理要快得多。

标签: python queue webserver batch-processing


【解决方案1】:

我建议使用简单的 python 微型 web 框架,例如瓶子。然后,您将通过队列将请求发送到后台进程(从而允许连接结束)。

然后,后台进程将有一个连续循环来检查您的条件(时间和数量),并在满足条件后执行该工作。

编辑:

这是一个示例网络服务器,它在将项目发送到您想要使用的任何排队系统之前对其进行批处理(RabbitMQ 对我来说总是使用 Python 过于复杂。我以前使用过 Celery 和其他更简单的排队系统)。这样后端只需从队列中抓取一个“项目”,它将包含所有必需的 50 个请求。

import bottle
import threading
import Queue


app = bottle.Bottle()

app.queue = Queue.Queue()


def send_to_rabbitMQ(items):
    """Custom code to send to rabbitMQ system"""
    print("50 items gathered, sending to rabbitMQ")


def batcher(queue):
    """Background thread that gathers incoming requests"""
    while True:
        batcher_loop(queue)


def batcher_loop(queue):
    """Loop that will run until it gathers 50 items,
    then will call then function 'send_to_rabbitMQ'"""
    count = 0
    items = []
    while count < 50:
        try:
            next_item = queue.get(timeout=.5)
        except Queue.Empty:
            pass
        else:
            items.append(next_item)
            count += 1

    send_to_rabbitMQ(items)


@app.route("/add_request", method=["PUT", "POST"])
def add_request():
    """Simple bottle request that grabs JSON and puts it in the queue"""
    request = bottle.request.json['request']
    app.queue.put(request)


if __name__ == '__main__':
    t = threading.Thread(target=batcher, args=(app.queue, ))
    t.daemon = True  # Make sure the background thread quits when the program ends
    t.start()

    bottle.run(app)

用于测试的代码:

import requests
import json

for i in range(101):
    req = requests.post("http://localhost:8080/add_request",
                        data=json.dumps({"request": 1}),
                        headers={"Content-type": "application/json"})

【讨论】:

  • 谢谢 CasualDemon。我想,我之前不是很清楚。我添加了一张图片并编辑了描述以更好地解释我的问题。
  • @ankit 我已经更新了我的答案,至少让您了解网络服务器的外观。希望这可以引导您朝着正确的方向前进。
  • 谢谢@CasualDemon,我还需要在后端完成处理后向浏览器回复结果。怎么可能实现?
猜你喜欢
  • 1970-01-01
  • 2011-08-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多