我的堆栈是带有 gevents 的 uwsgi。我正在尝试用装饰器包装我的 api 端点,以将所有请求数据(url、方法、正文和响应)推送到 kafka 主题,但它不起作用。我的理论是因为我正在使用 gevents,并且我试图在异步模式下运行这些,实际上推送到 kafka 的异步线程无法使用 gevents 运行。如果我尝试使方法同步,那么它也不起作用,它在生产工人中死去,即在生产之后调用永远不会返回。虽然这两种方法在 python shell 上运行良好,如果我在线程上运行 uwsgi。
遵循示例代码: 1. 使用 kafka-python (async)
try:
kafka_producer = KafkaProducer(bootstrap_servers=KAFKAHOST.split(','))
except NoBrokersAvailable:
logger.info(u'Kafka Host not available: {}'.format(KAFKAHOST))
kafka_producer = None
def send_message_to_kafka(topic, key, message):
"""
:param topic: topic name
:param key: key to decide partition
:param message: json serializable object to send
:return:
"""
if not kafka_producer:
logger.info(u'Kafka Host not available: {}'.format(KAFKAHOST))
return
data = json.dumps(message)
try:
start = time.time()
kafka_producer.send(topic, key=str(key), value=data)
logger.info(u'Time take to push to Kafka: {}'.format(time.time() - start))
except KafkaTimeoutError as e:
logger.info(u'Message not sent: {}'.format(KAFKAHOST))
logger.info(e)
pass
except Exception as e:
logger.info(u'Message not sent: {}'.format(KAFKAHOST))
logger.exception(e)
pass
使用 py-kafka(同步):
try: client = KafkaClient(hosts=KAFKAHOST) except Exception as e: logger.info(u'Kafka Host Not Found: {}'.format(KAFKAHOST)) client = None def send_message_to_kafka(topic, key, message): """ :param topic: topic name :param key: key to decide partition :param message: json serializable object to send :return: """ if not client: logger.info(u'Kafka Host is None') return data = json.dumps(message) try: start = time.time() topic = client.topics[topic] with topic.get_sync_producer() as producer: producer.produce(data, partition_key='{}'.format(key)) logger.info(u'Time take to push to Kafka: {}'.format(time.time() - start)) except Exception as e: logger.exception(e) pass