我有一个Django应用程序,该应用程序具有与Kafka集成的功能,可以处理一些订单。 Kafka队列上的主题是动态创建的,因此也必须动态订阅使用者。 现在,当我初始化使用者时,它将阻塞主线程,因此我必须在后台线程中启动使用者,但是我看不到任何打印语句,因此我不确定使用者是否已初始化,也不确定这样做的正确方法?
def kafka_consumer(topic) :
try :
if topic is None :
raise Exception("Topic is none, unable to initialize kafka consumer")
conf = {'bootstrap.servers': "localhost:9092", 'group.id': 'test', 'session.timeout.ms': 6000,
'auto.offset.reset': 'earliest'}
c = Consumer(conf)
print("Subscribing consumer to topic ",topic[0])
c.subscribe(topic)
# Read messages from Kafka, print to stdout
try:
while True:
msg = c.poll(timeout=1.0)
if msg is None:
continue
if msg.error():
raise KafkaException(msg.error())
else:
sys.stderr.write('%% %s [%d] at offset %d with key %s:\n' %
(msg.topic(), msg.partition(), msg.offset(),
str(msg.key())))
try :
print(json.loads(msg.value()))
print("---------------------------------")
objs = serializers.deserialize("json", msg.value())
for obj in objs :
print(obj)
print(obj.object)
except Exception as e :
import traceback
print(traceback.format_exc())
except Exception as e:
import traceback
print(traceback.format_exc())
finally:
c.close()
except Exception as e:
import traceback
print(traceback.format_exc())
下面是我如何调用函数:
try :
topic = []
topic.append(offer.offering_order_id)
background_thread = Thread(target=kafka_consumer, args=(topic))
background_thread.start()
except Exception as e :
import traceback
print(traceback.format_exc())
有人可以帮助我解决架构问题吗?