You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

82 lines
2.5KB

  1. # -*- coding: utf-8 -*-
  2. import time
  3. from loguru import logger
  4. from queue import Queue
  5. from threading import Thread
  6. from util import KafkaUtils
  7. '''
  8. 实时、离线消息拉取线程
  9. '''
  10. class MessagePollingThread(Thread):
  11. # 实时流分析消息拉取线程
  12. def __init__(self, name, cfg):
  13. super().__init__()
  14. self.name = name
  15. self.cfg = cfg
  16. self.msgQueue = Queue()
  17. def getMsgQueue(self):
  18. eBody = None
  19. try:
  20. eBody = self.msgQueue.get(block=False)
  21. except Exception as e:
  22. pass
  23. return eBody
  24. def run(self):
  25. logger.info("{} 线程任务开始执行", self.name)
  26. # 指令消息消费
  27. customerKafkaConsumer = KafkaUtils.CustomerKafkaConsumer(self.cfg["content"])
  28. customerKafkaConsumer.subscribe(topics=self.cfg["topics"])
  29. while True:
  30. try:
  31. if self.msgQueue.qsize() > 0:
  32. time.sleep(2)
  33. continue
  34. if customerKafkaConsumer.customerConsumer is None:
  35. customerKafkaConsumer.get_consumer()
  36. customerKafkaConsumer.subscribe(topics=self.cfg["topics"])
  37. # 拉取消息问题 1:后面运行会吃力,建议每次一条一拉
  38. msg = customerKafkaConsumer.customerConsumer.poll()
  39. if msg is not None and len(msg) > 0:
  40. self.msgQueue.put(msg)
  41. for k, v in msg.items():
  42. for m in v:
  43. customerKafkaConsumer.commit_offset(m)
  44. except Exception as e:
  45. logger.error("消息监听异常:")
  46. logger.exception(e)
  47. time.sleep(1)
  48. def poll(self):
  49. if self.msgQueue.qsize() > 0:
  50. return self.getMsgQueue()
  51. return None
  52. class OnlineMessagePollingThread(MessagePollingThread):
  53. # 实时流分析消息拉取线程
  54. pass
  55. class OfflineMessagePollingThread(MessagePollingThread):
  56. # 实时流分析消息拉取线程
  57. pass
  58. # if __name__ == '__main__':
  59. # t1 = OnlineMessagePollingThread('t1', {'bootstrap_servers': [
  60. # 'localhost:9092'], 'group_id': 'algSch', 'topics': ('alg_online_tasks',)})
  61. # t1.start()
  62. #
  63. # t2 = OfflineMessagePollingThread('t2', {'bootstrap_servers': [
  64. # 'localhost:9092'], 'group_id': 'algSch', 'topics': ('alg_offline_tasks',)})
  65. # t2.start()
  66. #
  67. # while True:
  68. # print(t1.poll())
  69. # print(t2.poll())
  70. # time.sleep(1)