python 异步消息队列

参考: 

http://blog.chinaunix.net/uid-429659-id-3985612.html

https://docs.python.org/2/library/queue.html

 

注意:

queue模块是python3自带的模块, python2自带的是Queue

网上是就贴了一段代码, 其他的什么也没有, 看了之后, 心中一万只*草*泥*马奔过啊

 

参考代码

  1. #!/usr/bin/env python
  2. -*- coding: UTF--*-
  3. import logging
  4. import queue
  5. import threading
  6. def func_a(a, b):
  7.     return a + b
  8. def func_b():
  9.     pass
  10. def func_c(a, b, c):
  11.     return a, b, c
  12. # 异步任务队列
  13. _task_queue = queue.Queue()
  14. def async_call(function, callback, *args, **kwargs):
  15.     _task_queue.put({
  16.         'function': function,
  17.         'callback': callback,
  18.         'args': args,
  19.         'kwargs': kwargs
  20.     })
  21. def _task_queue_consumer():
  22.     """
  23.     异步任务队列消费者
  24.     """
  25.     while True:
  26.         try:
  27.             task = _task_queue.get()
  28.             function = task.get('function')
  29.             callback = task.get('callback')
  30.             args = task.get('args')
  31.             kwargs = task.get('kwargs')
  32.             try:
  33.                 if callback:
  34.                     callback(function(*args, **kwargs))
  35.             except Exception as ex:
  36.                 if callback:
  37.                     callback(ex)
  38.             finally:
  39.                 _task_queue.task_done()
  40.         except Exception as ex:
  41.             logging.warning(ex)
  42. def handle_result(result):
  43.     print(type(result), result)
  44. if __name__ == '__main__':
  45.     t = threading.Thread(target=_task_queue_consumer)
  46.     t.daemon = True
  47.     t.start()
  48.     async_call(func_a, handle_result, 1, 2)
  49.     async_call(func_b, handle_result)
  50.     async_call(func_c, handle_result, 1, 2, 3)
  51.     async_call(func_c, handle_result, 1, 2, 3, 4)
  52.     _task_queue.join()

你可能感兴趣的:(python 异步消息队列)