如何使用Python中的confluent-kafka发送和使用json消息

问题描述 投票:1回答:1

我是Python的新手并开始使用Kafka。所以我设置了一个Kafka经纪人,我正在尝试使用confluent-kafka与它进行通信。我已经能够使用它生成和使用简单的消息,但是,我有一些django对象,我需要序列化并发送它ti kafka。

以前我使用kafka-python,我能够发送和使用json消息,但是我有一些奇怪的问题。

#Producer.py

def send_message(topic,message) :
try :
    try :
        p.produce(topic,message,callback=delivery_callback)
    except BufferError as b :
        sys.stderr.write('%% Local producer queue is full (%d messages awaiting delivery): try again\n' %len(p))
    # Serve delivery callback queue.
    # NOTE: Since produce() is an asynchronous API this poll() call
    #       will most likely not serve the delivery callback for the
    #       last produce()d message.
    p.poll(0)
    # Wait until all messages have been delivered
    sys.stderr.write('%% Waiting for %d deliveries\n' % len(p))
    p.flush()
except Exception as e :
    import traceback
    print(traceback.format_exc())

#Consumer.py

conf = {'bootstrap.servers': "localhost:9092", 'group.id': 'test', 'session.timeout.ms': 6000,
        'auto.offset.reset': 'earliest'}
c = Consumer(conf)
c.subscribe(["mykafka"])
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())))
            print(msg.value())
except Exception as e:
    import traceback
    print(traceback.format_exc())
finally:
    c.close()

我像这样序列化我的django模型对象:

from django.core import serializers
# assuming obj is a model instance
serialized_obj = serializers.serialize('json', [ obj, ])

那么我需要在生产者和消费者中制作和使用json消息进行哪些更改?

django python-3.x apache-kafka confluent confluent-kafka
1个回答
0
投票

试试制片人

send_message(topic, serialized_obj)

而对于消费者来说,你要将字节去除字符串

print(msg.value().decode('utf8'))

如果你需要json对象,那么你可以使用json.loads

© www.soinside.com 2019 - 2024. All rights reserved.