-
Notifications
You must be signed in to change notification settings - Fork 933
Add context manager support for Producer, Consumer, and AdminClient #2114
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
df0a414
Enable context manager for producer
k-raina 45b4385
Enable context manager for consumer
k-raina a762287
Update schema registry example to use with clause
k-raina 1016097
Enable context manager for admin
k-raina 159d09e
Add example for producer consumer and admin with clause
k-raina ca434b9
Fix linting
k-raina File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,131 @@ | ||
| #!/usr/bin/env python | ||
| # | ||
| # Copyright 2016 Confluent Inc. | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
| # | ||
|
|
||
| # | ||
| # Example demonstrating context manager usage for Producer, Consumer, and AdminClient. | ||
| # Context managers ensure proper cleanup of resources when exiting the 'with' block. | ||
| # | ||
|
|
||
| from confluent_kafka import Producer, Consumer, KafkaError | ||
| from confluent_kafka.admin import AdminClient, NewTopic | ||
| import sys | ||
|
|
||
|
|
||
| def main(): | ||
| if len(sys.argv) < 2: | ||
| sys.stderr.write('Usage: %s <bootstrap-brokers>\n' % sys.argv[0]) | ||
| sys.exit(1) | ||
|
|
||
| broker = sys.argv[1] | ||
| topic = 'context-manager-example' | ||
|
|
||
| # Example 1: AdminClient with context manager | ||
| # Automatically destroys the admin client when exiting the 'with' block | ||
| print("=== AdminClient Context Manager Example ===") | ||
| admin_conf = {'bootstrap.servers': broker} | ||
|
|
||
| with AdminClient(admin_conf) as admin: | ||
| # Create a topic using AdminClient | ||
| topic_obj = NewTopic(topic, num_partitions=1, replication_factor=1) | ||
| futures = admin.create_topics([topic_obj]) | ||
|
|
||
| # Wait for the operation to complete | ||
| for topic_name, future in futures.items(): | ||
| try: | ||
| future.result() # The result itself is None | ||
| print(f"Topic '{topic_name}' created successfully") | ||
| except Exception as e: | ||
| print(f"Failed to create topic '{topic_name}': {e}") | ||
|
|
||
| # Poll to ensure callbacks are processed | ||
| admin.poll(timeout=1.0) | ||
|
|
||
| # AdminClient is automatically destroyed here, no need for manual cleanup | ||
|
|
||
| # Example 2: Producer with context manager | ||
| # Automatically flushes pending messages and destroys the producer | ||
| print("\n=== Producer Context Manager Example ===") | ||
| producer_conf = {'bootstrap.servers': broker} | ||
|
|
||
| def delivery_callback(err, msg): | ||
| if err: | ||
| print(f'Message failed delivery: {err}') | ||
| else: | ||
| print(f'Message delivered to {msg.topic()} [{msg.partition()}] @ offset {msg.offset()}') | ||
|
|
||
| with Producer(producer_conf) as producer: | ||
| # Produce some messages | ||
| for i in range(5): | ||
| value = f'Message {i} from context manager example' | ||
| producer.produce( | ||
| topic, | ||
| key=f'key-{i}', | ||
| value=value.encode('utf-8'), | ||
| callback=delivery_callback | ||
| ) | ||
| # Poll for delivery callbacks | ||
| producer.poll(0) | ||
|
|
||
| print(f"Produced 5 messages to topic '{topic}'") | ||
|
|
||
| # Producer automatically flushes all pending messages and destroys here | ||
| # No need to call producer.flush() or manually clean up | ||
|
|
||
| # Example 3: Consumer with context manager | ||
| # Automatically closes the consumer (leaves consumer group, commits offsets) | ||
| print("\n=== Consumer Context Manager Example ===") | ||
| consumer_conf = { | ||
| 'bootstrap.servers': broker, | ||
| 'group.id': 'context-manager-example-group', | ||
| 'auto.offset.reset': 'earliest' | ||
| } | ||
|
|
||
| with Consumer(consumer_conf) as consumer: | ||
| # Subscribe to the topic | ||
| consumer.subscribe([topic]) | ||
|
|
||
| # Consume messages | ||
| msg_count = 0 | ||
| try: | ||
| while msg_count < 5: | ||
| msg = consumer.poll(timeout=1.0) | ||
| if msg is None: | ||
| continue | ||
|
|
||
| if msg.error(): | ||
| if msg.error().code() == KafkaError._PARTITION_EOF: | ||
| # End of partition, try next message | ||
| continue | ||
| else: | ||
| print(f'Consumer error: {msg.error()}') | ||
| break | ||
|
|
||
| print(f'Consumed message: key={msg.key().decode("utf-8")}, ' | ||
| f'value={msg.value().decode("utf-8")}, ' | ||
| f'partition={msg.partition()}, offset={msg.offset()}') | ||
| msg_count += 1 | ||
| except KeyboardInterrupt: | ||
| print('Consumer interrupted by user') | ||
|
|
||
| # Consumer automatically calls close() here (leaves group, commits offsets) | ||
| # No need to manually call consumer.close() | ||
|
|
||
| print("\n=== All examples completed successfully! ===") | ||
|
|
||
|
|
||
| if __name__ == '__main__': | ||
| main() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The avro_serializer is created inside the SchemaRegistryClient context but used in the Producer context. This creates a dependency where the serializer references a potentially closed schema registry client. Consider restructuring to ensure the schema registry client remains open for the lifetime of the serializer.