Setup

The Pulsar client is based on the C++ client and may have problems installing on windows

pip install pulsar-client==2.4.0

Simple Producer and Consumer

Producer example This creates a Python producer for the my-topic topic and send 10 messages on that topic:

import pulsar
 
client = pulsar.Client('pulsar://localhost:6650')
 
producer = client.create_producer('my-topic')
 
for i in range(10):
    producer.send(('Hello-%d' % i).encode('utf-8'))
 
client.close()

Consumer example This creates a consumer with the my-subscription subscription on the my-topic topic, listen for incoming messages, print the content and ID of messages that arrive, and acknowledge each message to the Pulsar broker:

consumer = client.subscribe('my-topic', 'my-subscription')
 
while True:
    msg = consumer.receive()
    try:
        print("Received message '{}' id='{}'".format(msg.data(), msg.message_id()))
        # Acknowledge successful processing of the message
        consumer.acknowledge(msg)
    except:
        # Message failed to be processed
        consumer.negative_acknowledge(msg)
 
client.close()
 
python_pulsar.txt · Last modified: 2019/07/24 00:46 by root
 
RSS - 200 © CrosswireDigitialMedia Ltd