python - 在 ZeroRPC 中实现自定义队列

标签 python zeromq

目前,我正在使用 ZeroRPC,我让“工作人员”连接到“服务器”并执行服务器发送给他们的工作。

目前,只要有调用,就会通过 ZeroRPC 进行调用,据我所知,它使用 FIFO 队列。

我想使用自己的队列,以便对调用进行限制/优先排序。

我希望 ZeroRPC 公开一个 gevent Event,当其内部队列空时触发。

最佳答案

您想要做的是在服务器中创建自己的工作队列。并按照您希望的优先级为您自己安排调用。

由于几行代码比 3 卷中的任何吸血鬼故事都表达得更多,让我们用伪代码看看服务器可能是什么样子:

myqueue = MySuperBadAssQueue()

def myqueueprocessor():
  for request in myqueue: # blocks until next request
    gevent.spawn(request.processme) # do the job asynchronously

gevent.spawn(myqueueprocessor) # do that at startup

class Server:

  def dosomething(args...blabla...):  # what users are calling
    request = Request(args...blabla...)
    myqueue.put(request)  # something to do buddy!
    return request.future.get() # return when request is completed
                                # (can also raise an exception)

# An example of what a request could look like:
class Request:
  def __init__(self, ....blablabla...):
    self.future = gevent.AsyncResult()

   def process():
     try:
         result = someworker(self.args*) # call some worker
         self.future.set(result) # complete the initial request
     except Exception as e:
         self.future.set_exception(e)

由 MySuperBadAssQueue 来完成所有智能工作,如果需要的话可以节流,如果需要的话取消带有异常的请求,等等......

ZeroRPC 不会公开任何事件来让您知道其“内部”队列是否运行 空:

In fact, there is no explicit queue in ZeroRPC. What happens, is simply first come first serve, and the exact order depend both of ZeroMQ and the Gevent IOLoop (libevent or libev depending of the version). It happens that in practice, this conveniently plays like a FIFO queue.

关于python - 在 ZeroRPC 中实现自定义队列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13724387/

相关文章:

python - 如何使用 WTForms 和 SQLAlchemy 填充多对多关系?

javascript - 如何使用nodejs Zeromq库设置双向消息 channel ?

c++ - ZeroMQ 服务器如何维护与所有客户端的连接?

Go 的垃圾收集器在使用时删除 ZeroMQ 套接字

python - 使用 OpenCV python 和多线程运行两个视频

python - 如何根据 2 个可能的值检查变量?

python - 无法让 ZeroMQ python 绑定(bind)通过 IPC 接收消息

python - ZeroMQ 轮询器 vs Tornados EventLoop

python - 使用圆角坐标在 Python 中序列化 GeoJSON

Python - 使用 unicode 抓取网站