|
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172 |
- from confluent_kafka import Producer, Consumer, KafkaException, KafkaError
- import os,time
- from config import conf
-
- kafka_client = None
-
- class KafkaClient:
- def __init__(self):
-
- bootstrap_servers=conf().get("kafka_bootstrap_servers")
- agent_tel=os.environ.get('tel', '18029274615')
- consumer_group=f'aiops-wx_{agent_tel}'
- print(f'kafka消费组 {consumer_group}')
- topic="topic.ai.ops.wx"
-
- self.bootstrap_servers = bootstrap_servers
- self.consumer_group = consumer_group
- self.topic = topic
-
- self.producer = Producer({'bootstrap.servers': self.bootstrap_servers})
- self.consumer = Consumer({
- 'bootstrap.servers': self.bootstrap_servers,
- 'group.id': self.consumer_group,
- 'auto.offset.reset': 'earliest',
-
- 'enable.auto.commit': True
- })
-
- def delivery_report(self, err, msg):
- """
- 回调函数,用于确认消息是否成功发送
- """
- if err is not None:
- print(f"Message delivery failed: {err}")
- else:
- print(f"Message delivered to {msg.topic()} [{msg.partition()}] @ {msg.offset()}")
-
- def produce_messages(self, messages):
- """
- 发送消息
- """
- try:
- for message in messages:
- self.producer.produce(self.topic, value=message, callback=self.delivery_report)
- print(f"Produced: {message}")
- self.producer.poll(0)
- except Exception as e:
- print(f"An error occurred: {e}")
- finally:
- self.producer.flush()
-
- def produce_message(self, message):
- """
- 发送消息
- """
- try:
- self.producer.produce(self.topic, value=message, callback=self.delivery_report)
-
- self.producer.poll(0)
- except Exception as e:
- print(f"An error occurred: {e}")
- finally:
- self.producer.flush()
-
- def consume_messages(self,process_callback):
- """
- 消费消息并调用回调处理业务逻辑,只有当回调返回 True 时才提交偏移量
- :param process_callback: 业务逻辑回调函数,返回布尔值
- :param user_nickname: 用户昵称
- """
- self.consumer.subscribe([self.topic])
-
- try:
- while True:
- msg = self.consumer.poll(0.3)
- if msg is None:
- continue
- if msg.error():
- if msg.error().code() == KafkaError._PARTITION_EOF:
- print(f"End of partition {msg.partition}, offset {msg.offset()}")
- else:
- raise KafkaException(msg.error())
- else:
-
-
-
- process_callback(msg.value().decode('utf-8'))
-
-
-
-
-
-
-
-
- except KeyboardInterrupt:
- print("消费中断")
- finally:
- self.consumer.close()
-
- def consume_messages(self,agent_tel,process_callback):
- """
- 消费消息并调用回调处理业务逻辑,只有当回调返回 True 时才提交偏移量
- :param process_callback: 业务逻辑回调函数,返回布尔值
- :param agent_tel: 代理商手机号
- """
- consumer=Consumer({
- 'bootstrap.servers': self.bootstrap_servers,
- 'group.id': f'aiops-wx_{agent_tel}',
- 'auto.offset.reset': 'earliest',
-
- 'enable.auto.commit': True
- })
- consumer.subscribe([self.topic])
-
- try:
- while True:
- msg = consumer.poll(0.3)
- if msg is None:
- continue
- if msg.error():
- if msg.error().code() == KafkaError._PARTITION_EOF:
- print(f"End of partition {msg.partition}, offset {msg.offset()}")
- else:
- raise KafkaException(msg.error())
- else:
-
-
-
- process_callback(agent_tel,msg.value().decode('utf-8'))
-
-
-
-
-
-
-
-
- except KafkaException as e:
- print(f"Kafka exception occurred: {e}")
- if 'KafkaError._ALL_BROKERS_DOWN' in str(e):
- print(f"Kafka brokers for agent {agent_tel} are down, retrying in 5 seconds...")
- time.sleep(5)
- self._reconnect_consumer_with_agent_tel(consumer, agent_tel)
- except Exception as e:
- print(f"An unexpected error occurred: {e}")
- time.sleep(5)
-
-
- def _reconnect_consumer_with_agent_tel(self, consumer, agent_tel):
- """
- 尝试为指定的代理商重新连接 Kafka 消费者
- """
- print(f"Attempting to reconnect Kafka consumer for agent {agent_tel}...")
- try:
- consumer.close()
- consumer = Consumer({
- 'bootstrap.servers': self.bootstrap_servers,
- 'group.id': f'aiops-wx_{agent_tel}',
- 'auto.offset.reset': 'earliest',
- 'enable.auto.commit': True
- })
- consumer.subscribe([self.topic])
- print(f"Reconnected successfully for agent {agent_tel}.")
- except KafkaException as e:
- print(f"Error while reconnecting for agent {agent_tel}: {e}")
- time.sleep(5)
-
-
- def start():
- global kafka_client
- kafka_client = KafkaClient()
|