Skip to content

Commit fd1e041

Browse files
committed
Fix: handle topic alreadyExistsError
1 parent 25a3e7d commit fd1e041

File tree

1 file changed

+14
-6
lines changed

1 file changed

+14
-6
lines changed

examples/mysql_to_kafka.py

+14-6
Original file line numberDiff line numberDiff line change
@@ -23,12 +23,20 @@
2323
def create_kafka_topic(topic_name, num_partitions=1, replication_factor=1):
2424
admin_client = KafkaAdminClient(bootstrap_servers="127.0.0.1:9092")
2525

26-
topic = NewTopic(
27-
name=topic_name,
28-
num_partitions=num_partitions,
29-
replication_factor=replication_factor,
30-
)
31-
admin_client.create_topics(new_topics=[topic])
26+
topic_exists = False
27+
try:
28+
topic_listings = admin_client.list_topics()
29+
topic_exists = topic_name in topic_listings
30+
except TopicAlreadyExistsError:
31+
topic_exists = True
32+
33+
if not topic_exists:
34+
topic = NewTopic(
35+
name=topic_name,
36+
num_partitions=num_partitions,
37+
replication_factor=replication_factor,
38+
)
39+
admin_client.create_topics(new_topics=[topic])
3240

3341

3442
def main():

0 commit comments

Comments
 (0)