|
| 1 | +#!/usr/bin/env python |
| 2 | +# |
| 3 | +# Copyright 2016 Confluent Inc. |
| 4 | +# |
| 5 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 6 | +# you may not use this file except in compliance with the License. |
| 7 | +# You may obtain a copy of the License at |
| 8 | +# |
| 9 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | +# |
| 11 | +# Unless required by applicable law or agreed to in writing, software |
| 12 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | +# See the License for the specific language governing permissions and |
| 15 | +# limitations under the License. |
| 16 | +# |
| 17 | + |
| 18 | +# |
| 19 | +# Example demonstrating context manager usage for Producer, Consumer, and AdminClient. |
| 20 | +# Context managers ensure proper cleanup of resources when exiting the 'with' block. |
| 21 | +# |
| 22 | + |
| 23 | +from confluent_kafka import Producer, Consumer, KafkaError |
| 24 | +from confluent_kafka.admin import AdminClient, NewTopic |
| 25 | +import sys |
| 26 | + |
| 27 | + |
| 28 | +def main(): |
| 29 | + if len(sys.argv) < 2: |
| 30 | + sys.stderr.write('Usage: %s <bootstrap-brokers>\n' % sys.argv[0]) |
| 31 | + sys.exit(1) |
| 32 | + |
| 33 | + broker = sys.argv[1] |
| 34 | + topic = 'context-manager-example' |
| 35 | + |
| 36 | + # Example 1: AdminClient with context manager |
| 37 | + # Automatically destroys the admin client when exiting the 'with' block |
| 38 | + print("=== AdminClient Context Manager Example ===") |
| 39 | + admin_conf = {'bootstrap.servers': broker} |
| 40 | + |
| 41 | + with AdminClient(admin_conf) as admin: |
| 42 | + # Create a topic using AdminClient |
| 43 | + topic_obj = NewTopic(topic, num_partitions=1, replication_factor=1) |
| 44 | + futures = admin.create_topics([topic_obj]) |
| 45 | + |
| 46 | + # Wait for the operation to complete |
| 47 | + for topic_name, future in futures.items(): |
| 48 | + try: |
| 49 | + future.result() # The result itself is None |
| 50 | + print(f"Topic '{topic_name}' created successfully") |
| 51 | + except Exception as e: |
| 52 | + print(f"Failed to create topic '{topic_name}': {e}") |
| 53 | + |
| 54 | + # Poll to ensure callbacks are processed |
| 55 | + admin.poll(timeout=1.0) |
| 56 | + |
| 57 | + # AdminClient is automatically destroyed here, no need for manual cleanup |
| 58 | + |
| 59 | + # Example 2: Producer with context manager |
| 60 | + # Automatically flushes pending messages and destroys the producer |
| 61 | + print("\n=== Producer Context Manager Example ===") |
| 62 | + producer_conf = {'bootstrap.servers': broker} |
| 63 | + |
| 64 | + def delivery_callback(err, msg): |
| 65 | + if err: |
| 66 | + print(f'Message failed delivery: {err}') |
| 67 | + else: |
| 68 | + print(f'Message delivered to {msg.topic()} [{msg.partition()}] @ offset {msg.offset()}') |
| 69 | + |
| 70 | + with Producer(producer_conf) as producer: |
| 71 | + # Produce some messages |
| 72 | + for i in range(5): |
| 73 | + value = f'Message {i} from context manager example' |
| 74 | + producer.produce( |
| 75 | + topic, |
| 76 | + key=f'key-{i}', |
| 77 | + value=value.encode('utf-8'), |
| 78 | + callback=delivery_callback |
| 79 | + ) |
| 80 | + # Poll for delivery callbacks |
| 81 | + producer.poll(0) |
| 82 | + |
| 83 | + print(f"Produced 5 messages to topic '{topic}'") |
| 84 | + |
| 85 | + # Producer automatically flushes all pending messages and destroys here |
| 86 | + # No need to call producer.flush() or manually clean up |
| 87 | + |
| 88 | + # Example 3: Consumer with context manager |
| 89 | + # Automatically closes the consumer (leaves consumer group, commits offsets) |
| 90 | + print("\n=== Consumer Context Manager Example ===") |
| 91 | + consumer_conf = { |
| 92 | + 'bootstrap.servers': broker, |
| 93 | + 'group.id': 'context-manager-example-group', |
| 94 | + 'auto.offset.reset': 'earliest' |
| 95 | + } |
| 96 | + |
| 97 | + with Consumer(consumer_conf) as consumer: |
| 98 | + # Subscribe to the topic |
| 99 | + consumer.subscribe([topic]) |
| 100 | + |
| 101 | + # Consume messages |
| 102 | + msg_count = 0 |
| 103 | + try: |
| 104 | + while msg_count < 5: |
| 105 | + msg = consumer.poll(timeout=1.0) |
| 106 | + if msg is None: |
| 107 | + continue |
| 108 | + |
| 109 | + if msg.error(): |
| 110 | + if msg.error().code() == KafkaError._PARTITION_EOF: |
| 111 | + # End of partition, try next message |
| 112 | + continue |
| 113 | + else: |
| 114 | + print(f'Consumer error: {msg.error()}') |
| 115 | + break |
| 116 | + |
| 117 | + print(f'Consumed message: key={msg.key().decode("utf-8")}, ' |
| 118 | + f'value={msg.value().decode("utf-8")}, ' |
| 119 | + f'partition={msg.partition()}, offset={msg.offset()}') |
| 120 | + msg_count += 1 |
| 121 | + except KeyboardInterrupt: |
| 122 | + print('Consumer interrupted by user') |
| 123 | + |
| 124 | + # Consumer automatically calls close() here (leaves group, commits offsets) |
| 125 | + # No need to manually call consumer.close() |
| 126 | + |
| 127 | + print("\n=== All examples completed successfully! ===") |
| 128 | + |
| 129 | + |
| 130 | +if __name__ == '__main__': |
| 131 | + main() |
0 commit comments