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

时间:2019-04-14 06:01:04

标签: django python-3.x apache-kafka confluent confluent-kafka

我刚接触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消息?

1 个答案:

答案 0 :(得分:0)

尝试制作人

with ... <the same as above>
select id from second_query
minus
select id from first_query

使用者,您会将字节序列化为一个字符串

send_message(topic, serialized_obj)

如果您需要json对象,则可以使用print(msg.value().decode('utf8'))