TDengine/docs/examples/python/tmq_native.py

173 lines
5.7 KiB
Python
Raw Normal View History

#!/usr/bin/python3
import taos
db = "power"
topic = "topic_meters"
user = "root"
password = "taosdata"
host = "localhost"
port = 6030
groupId = "group1"
clientId = "1"
tdConnWsScheme = "ws"
autoOffsetReset = "latest"
autoCommitState = "true"
autoCommitIntv = "1000"
2024-08-02 18:51:12 +00:00
def prepareMeta():
conn = None
2024-08-03 10:04:12 +00:00
try:
conn = taos.connect(host=host, user=user, password=password, port=port)
2024-08-03 10:04:12 +00:00
conn.execute(f"CREATE DATABASE IF NOT EXISTS {db}")
2024-08-02 18:51:12 +00:00
# change database. same as execute "USE db"
conn.select_db(db)
2024-08-02 18:51:12 +00:00
# create super table
conn.execute(
2024-08-03 10:04:12 +00:00
"CREATE STABLE IF NOT EXISTS power.meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (location BINARY(64), groupId INT)"
2024-08-02 18:51:12 +00:00
)
2024-08-02 18:51:12 +00:00
# ANCHOR: create_topic
# create topic
conn.execute(
f"CREATE TOPIC IF NOT EXISTS {topic} AS SELECT ts, current, voltage, phase, groupid, location FROM meters"
)
# ANCHOR_END: create_topic
sql = """
INSERT INTO
power.d1001 USING power.meters (groupid, location) TAGS(2, 'California.SanFrancisco')
VALUES (NOW + 1a, 10.30000, 219, 0.31000)
(NOW + 2a, 12.60000, 218, 0.33000) (NOW + 3a, 12.30000, 221, 0.31000)
power.d1002 USING power.meters (groupid, location) TAGS(3, 'California.SanFrancisco')
2024-08-02 18:51:12 +00:00
VALUES (NOW + 1a, 10.30000, 218, 0.25000)
"""
affectedRows = conn.execute(sql)
2024-08-12 12:28:31 +00:00
print(f"Inserted into {affectedRows} rows to power.meters successfully.")
2024-08-02 18:51:12 +00:00
except Exception as err:
print(f"Failed to prepareMeta, host: {host}:{port}, db: {db}, topic: {topic}, ErrMessage:{err}.")
2024-08-03 10:04:12 +00:00
raise err
finally:
2024-08-02 18:51:12 +00:00
if conn:
2024-08-03 10:04:12 +00:00
conn.close()
2024-08-03 13:58:17 +00:00
# ANCHOR: create_consumer
from taos.tmq import Consumer
2024-08-03 10:04:12 +00:00
2024-08-02 18:51:12 +00:00
def create_consumer():
try:
consumer = Consumer(
{
2024-08-12 06:13:31 +00:00
"group.id": groupId,
"client.id": clientId,
"td.connect.user": user,
"td.connect.pass": password,
"enable.auto.commit": autoCommitState,
"auto.commit.interval.ms": autoCommitIntv,
"auto.offset.reset": autoOffsetReset,
2024-08-12 06:13:31 +00:00
"td.connect.ip": host,
"td.connect.port": str(port),
2024-08-02 18:51:12 +00:00
}
)
print(f"Create consumer successfully, host: {host}:{port}, groupId: {groupId}, clientId: {clientId}")
2024-08-03 10:04:12 +00:00
return consumer
2024-08-02 18:51:12 +00:00
except Exception as err:
print(f"Failed to create native consumer, host: {host}:{port}, groupId: {groupId}, clientId: {clientId}, ErrMessage:{err}.")
2024-08-03 10:04:12 +00:00
raise err
# ANCHOR_END: create_consumer
# ANCHOR: subscribe
2024-08-02 18:51:12 +00:00
def subscribe(consumer):
try:
2024-08-03 15:32:14 +00:00
# subscribe to the topics
2024-08-02 18:51:12 +00:00
consumer.subscribe(["topic_meters"])
2024-08-12 12:28:31 +00:00
print("Subscribe topics successfully")
2024-08-02 18:51:12 +00:00
for i in range(50):
records = consumer.poll(1)
if records:
err = records.error()
if err is not None:
2024-08-12 12:28:31 +00:00
print(f"Poll data error, {err}")
2024-08-02 18:51:12 +00:00
raise err
2024-08-03 10:04:12 +00:00
val = records.value()
2024-08-02 18:51:12 +00:00
if val:
for block in val:
2024-08-12 06:13:31 +00:00
data = block.fetchall()
print(f"data: {data}")
2024-08-02 18:51:12 +00:00
except Exception as err:
print(f"Failed to poll data, topic: {topic}, groupId: {groupId}, clientId: {clientId}, ErrMessage:{err}.")
2024-08-02 18:51:12 +00:00
raise err
2024-08-03 10:04:12 +00:00
# ANCHOR_END: subscribe
2024-08-02 18:51:12 +00:00
def commit_offset(consumer):
# ANCHOR: commit_offset
try:
for i in range(50):
records = consumer.poll(1)
if records:
err = records.error()
if err is not None:
2024-08-12 12:28:31 +00:00
print(f"Poll data error, {err}")
2024-08-02 18:51:12 +00:00
raise err
2024-08-03 10:04:12 +00:00
val = records.value()
2024-08-02 18:51:12 +00:00
if val:
for block in val:
2024-08-03 10:04:12 +00:00
print(block.fetchall())
2024-08-03 15:32:14 +00:00
# after processing the data, commit the offset manually
2024-08-02 18:51:12 +00:00
consumer.commit(records)
2024-08-12 12:28:31 +00:00
print("Commit offset manually successfully.");
2024-08-02 18:51:12 +00:00
except Exception as err:
print(f"Failed to commit offset, topic: {topic}, groupId: {groupId}, clientId: {clientId}, ErrMessage:{err}.")
2024-08-02 18:51:12 +00:00
raise err
# ANCHOR_END: commit_offset
2024-08-03 10:04:12 +00:00
2024-08-02 18:51:12 +00:00
def seek_offset(consumer):
# ANCHOR: assignment
2024-08-02 18:51:12 +00:00
try:
assignments = consumer.assignment()
2024-08-03 10:04:12 +00:00
if assignments:
for partition in assignments:
partition.offset = 0
consumer.seek(partition)
print(f"Assignment seek to beginning successfully.")
2024-08-02 18:51:12 +00:00
except Exception as err:
print(f"Failed to seek offset, topic: {topic}, groupId: {groupId}, clientId: {clientId}, ErrMessage:{err}.")
2024-08-02 18:51:12 +00:00
raise err
# ANCHOR_END: assignment
2024-08-02 18:51:12 +00:00
def unsubscribe(consumer):
2024-08-12 14:55:35 +00:00
# ANCHOR: unsubscribe
2024-08-02 18:51:12 +00:00
try:
consumer.unsubscribe()
2024-08-12 12:28:31 +00:00
print("Consumer unsubscribed successfully.");
2024-08-02 18:51:12 +00:00
except Exception as err:
print(f"Failed to unsubscribe consumer. topic: {topic}, groupId: {groupId}, clientId: {clientId}, ErrMessage:{err}.")
2024-08-12 14:55:35 +00:00
finally:
if consumer:
2024-08-14 08:25:22 +00:00
consumer.close()
print("Consumer closed successfully.");
2024-08-12 14:55:35 +00:00
# ANCHOR_END: unsubscribe
2024-08-02 18:51:12 +00:00
if __name__ == "__main__":
consumer = None
2024-08-03 10:04:12 +00:00
try:
2024-08-02 18:51:12 +00:00
prepareMeta()
consumer = create_consumer()
subscribe(consumer)
seek_offset(consumer)
commit_offset(consumer)
except Exception as err:
print(f"Failed to execute consumer example, topic: {topic}, groupId: {groupId}, clientId: {clientId}, ErrMessage:{err}.")
2024-08-02 18:51:12 +00:00
finally:
unsubscribe(consumer);