Merge pull request #27172 from taosdata/docs/sheyj-3.0
update conncetor log, keep same style
This commit is contained in:
commit
2c0a538f5c
|
@ -8,19 +8,15 @@ int main() {
|
||||||
const char *host = "localhost";
|
const char *host = "localhost";
|
||||||
const char *user = "root";
|
const char *user = "root";
|
||||||
const char *passwd = "taosdata";
|
const char *passwd = "taosdata";
|
||||||
// if don't want to connect to a default db, set it to NULL or ""
|
const char *db = NULL; // if don't want to connect to a default db, set it to NULL or ""
|
||||||
const char *db = NULL;
|
uint16_t port = 6030; // 0 means use the default port
|
||||||
uint16_t port = 0; // 0 means use the default port
|
|
||||||
TAOS *taos = taos_connect(host, user, passwd, db, port);
|
TAOS *taos = taos_connect(host, user, passwd, db, port);
|
||||||
if (taos == NULL) {
|
if (taos == NULL) {
|
||||||
int errno = taos_errno(NULL);
|
printf("Failed to connect to %s:%hu, ErrCode: 0x%x, ErrMessage: %s.\n", host, port, taos_errno(NULL), taos_errstr(NULL));
|
||||||
const char *msg = taos_errstr(NULL);
|
|
||||||
printf("%d, %s\n", errno, msg);
|
|
||||||
printf("failed to connect to server %s, errno: %d, msg: %s\n", host, errno, msg);
|
|
||||||
taos_cleanup();
|
taos_cleanup();
|
||||||
return -1;
|
return -1;
|
||||||
}
|
}
|
||||||
printf("success to connect server %s\n", host);
|
printf("Connected to %s:%hu successfully.\n", host, port);
|
||||||
|
|
||||||
/* put your code here for read and write */
|
/* put your code here for read and write */
|
||||||
|
|
||||||
|
|
|
@ -22,58 +22,57 @@
|
||||||
#include <string.h>
|
#include <string.h>
|
||||||
#include "taos.h"
|
#include "taos.h"
|
||||||
|
|
||||||
|
|
||||||
static int DemoCreateDB() {
|
static int DemoCreateDB() {
|
||||||
// ANCHOR: create_db_and_table
|
// ANCHOR: create_db_and_table
|
||||||
const char *ip = "localhost";
|
const char *host = "localhost";
|
||||||
const char *user = "root";
|
const char *user = "root";
|
||||||
const char *password = "taosdata";
|
const char *password = "taosdata";
|
||||||
|
uint16_t port = 6030;
|
||||||
|
int code = 0;
|
||||||
|
|
||||||
// connect
|
// connect
|
||||||
TAOS *taos = taos_connect(ip, user, password, NULL, 0);
|
TAOS *taos = taos_connect(host, user, password, NULL, port);
|
||||||
if (taos == NULL) {
|
if (taos == NULL) {
|
||||||
printf("failed to connect to server %s, reason: %s\n", ip, taos_errstr(NULL));
|
printf("Failed to connect to %s:%hu, ErrCode: 0x%x, ErrMessage: %s.\n", host, port, taos_errno(NULL),
|
||||||
taos_cleanup();
|
taos_errstr(NULL));
|
||||||
return -1;
|
taos_cleanup();
|
||||||
}
|
return -1;
|
||||||
printf("success to connect server %s\n", ip);
|
}
|
||||||
|
|
||||||
// create database
|
// create database
|
||||||
TAOS_RES *result = taos_query(taos, "CREATE DATABASE IF NOT EXISTS power");
|
TAOS_RES *result = taos_query(taos, "CREATE DATABASE IF NOT EXISTS power");
|
||||||
int code = taos_errno(result);
|
code = taos_errno(result);
|
||||||
if (code != 0) {
|
if (code != 0) {
|
||||||
printf("failed to create database power, reason: %s\n", taos_errstr(result));
|
printf("Failed to create database power, Server: %s:%hu, ErrCode: 0x%x, ErrMessage: %s.\n", host, port, code,
|
||||||
|
taos_errstr(result));
|
||||||
|
taos_close(taos);
|
||||||
|
taos_cleanup();
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
taos_free_result(result);
|
||||||
|
printf("Create database power successfully.\n");
|
||||||
|
|
||||||
|
// create table
|
||||||
|
const char *sql =
|
||||||
|
"CREATE STABLE IF NOT EXISTS power.meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (groupId "
|
||||||
|
"INT, location BINARY(24))";
|
||||||
|
result = taos_query(taos, sql);
|
||||||
|
code = taos_errno(result);
|
||||||
|
if (code != 0) {
|
||||||
|
printf("Failed to create stable power.meters, Server: %s:%hu, ErrCode: 0x%x, ErrMessage: %s\n.", host, port, code,
|
||||||
|
taos_errstr(result));
|
||||||
|
taos_close(taos);
|
||||||
|
taos_cleanup();
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
taos_free_result(result);
|
||||||
|
printf("Create stable power.meters successfully.\n");
|
||||||
|
|
||||||
|
// close & clean
|
||||||
taos_close(taos);
|
taos_close(taos);
|
||||||
taos_cleanup();
|
taos_cleanup();
|
||||||
return -1;
|
return 0;
|
||||||
}
|
// ANCHOR_END: create_db_and_table
|
||||||
taos_free_result(result);
|
|
||||||
printf("success to create database power\n");
|
|
||||||
|
|
||||||
// use database
|
|
||||||
result = taos_query(taos, "USE power");
|
|
||||||
taos_free_result(result);
|
|
||||||
|
|
||||||
// create table
|
|
||||||
const char* sql = "CREATE STABLE IF NOT EXISTS meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (groupId INT, location BINARY(24))";
|
|
||||||
result = taos_query(taos, sql);
|
|
||||||
code = taos_errno(result);
|
|
||||||
if (code != 0) {
|
|
||||||
printf("failed to create stable meters, reason: %s\n", taos_errstr(result));
|
|
||||||
taos_close(taos);
|
|
||||||
taos_cleanup();
|
|
||||||
return -1;
|
|
||||||
}
|
|
||||||
taos_free_result(result);
|
|
||||||
printf("success to create table meters\n");
|
|
||||||
|
|
||||||
// close & clean
|
|
||||||
taos_close(taos);
|
|
||||||
taos_cleanup();
|
|
||||||
return 0;
|
|
||||||
// ANCHOR_END: create_db_and_table
|
|
||||||
}
|
}
|
||||||
|
|
||||||
int main(int argc, char *argv[]) {
|
int main(int argc, char *argv[]) { return DemoCreateDB(); }
|
||||||
return DemoCreateDB();
|
|
||||||
}
|
|
||||||
|
|
|
@ -24,22 +24,19 @@
|
||||||
|
|
||||||
static int DemoInsertData() {
|
static int DemoInsertData() {
|
||||||
// ANCHOR: insert_data
|
// ANCHOR: insert_data
|
||||||
const char *ip = "localhost";
|
const char *host = "localhost";
|
||||||
const char *user = "root";
|
const char *user = "root";
|
||||||
const char *password = "taosdata";
|
const char *password = "taosdata";
|
||||||
|
uint16_t port = 6030;
|
||||||
|
int code = 0;
|
||||||
|
|
||||||
// connect
|
// connect
|
||||||
TAOS *taos = taos_connect(ip, user, password, NULL, 0);
|
TAOS *taos = taos_connect(host, user, password, NULL, port);
|
||||||
if (taos == NULL) {
|
if (taos == NULL) {
|
||||||
printf("failed to connect to server %s, reason: %s\n", ip, taos_errstr(NULL));
|
printf("Failed to connect to %s:%hu, ErrCode: 0x%x, ErrMessage: %s.\n", host, port, taos_errno(NULL), taos_errstr(NULL));
|
||||||
taos_cleanup();
|
taos_cleanup();
|
||||||
return -1;
|
return -1;
|
||||||
}
|
}
|
||||||
printf("success to connect server %s\n", ip);
|
|
||||||
|
|
||||||
// use database
|
|
||||||
TAOS_RES *result = taos_query(taos, "USE power");
|
|
||||||
taos_free_result(result);
|
|
||||||
|
|
||||||
// insert data, please make sure the database and table are already created
|
// insert data, please make sure the database and table are already created
|
||||||
const char* sql = "INSERT INTO " \
|
const char* sql = "INSERT INTO " \
|
||||||
|
@ -51,10 +48,10 @@ const char* sql = "INSERT INTO "
|
||||||
"power.d1002 USING power.meters TAGS(3, 'California.SanFrancisco') " \
|
"power.d1002 USING power.meters TAGS(3, 'California.SanFrancisco') " \
|
||||||
"VALUES " \
|
"VALUES " \
|
||||||
"(NOW + 1a, 10.30000, 218, 0.25000) ";
|
"(NOW + 1a, 10.30000, 218, 0.25000) ";
|
||||||
result = taos_query(taos, sql);
|
TAOS_RES *result = taos_query(taos, sql);
|
||||||
int code = taos_errno(result);
|
code = taos_errno(result);
|
||||||
if (code != 0) {
|
if (code != 0) {
|
||||||
printf("failed to insert data to power.meters, ip: %s, reason: %s\n", ip, taos_errstr(result));
|
printf("Failed to insert data to power.meters, Server: %s:%hu, ErrCode: 0x%x, ErrMessage: %s\n.", host, port, code, taos_errstr(result));
|
||||||
taos_close(taos);
|
taos_close(taos);
|
||||||
taos_cleanup();
|
taos_cleanup();
|
||||||
return -1;
|
return -1;
|
||||||
|
@ -63,7 +60,7 @@ taos_free_result(result);
|
||||||
|
|
||||||
// you can check affectedRows here
|
// you can check affectedRows here
|
||||||
int rows = taos_affected_rows(result);
|
int rows = taos_affected_rows(result);
|
||||||
printf("success to insert %d rows data to power.meters\n", rows);
|
printf("Successfully inserted %d rows into power.meters.\n", rows);
|
||||||
|
|
||||||
// close & clean
|
// close & clean
|
||||||
taos_close(taos);
|
taos_close(taos);
|
||||||
|
|
|
@ -25,29 +25,28 @@
|
||||||
|
|
||||||
static int DemoQueryData() {
|
static int DemoQueryData() {
|
||||||
// ANCHOR: query_data
|
// ANCHOR: query_data
|
||||||
const char *ip = "localhost";
|
const char *host = "localhost";
|
||||||
const char *user = "root";
|
const char *user = "root";
|
||||||
const char *password = "taosdata";
|
const char *password = "taosdata";
|
||||||
|
uint16_t port = 6030;
|
||||||
|
int code = 0;
|
||||||
|
|
||||||
// connect
|
// connect
|
||||||
TAOS *taos = taos_connect(ip, user, password, NULL, 0);
|
TAOS *taos = taos_connect(host, user, password, NULL, port);
|
||||||
if (taos == NULL) {
|
if (taos == NULL) {
|
||||||
printf("failed to connect to server %s, reason: %s\n", ip, taos_errstr(NULL));
|
printf("Failed to connect to %s:%hu, ErrCode: 0x%x, ErrMessage: %s.\n", host, port, taos_errno(NULL), taos_errstr(NULL));
|
||||||
taos_cleanup();
|
taos_cleanup();
|
||||||
return -1;
|
return -1;
|
||||||
}
|
}
|
||||||
printf("success to connect server %s\n", ip);
|
|
||||||
|
|
||||||
// use database
|
|
||||||
TAOS_RES *result = taos_query(taos, "USE power");
|
|
||||||
taos_free_result(result);
|
|
||||||
|
|
||||||
// query data, please make sure the database and table are already created
|
// query data, please make sure the database and table are already created
|
||||||
const char* sql = "SELECT ts, current, location FROM power.meters limit 100";
|
const char* sql = "SELECT ts, current, location FROM power.meters limit 100";
|
||||||
result = taos_query(taos, sql);
|
TAOS_RES *result = taos_query(taos, sql);
|
||||||
int code = taos_errno(result);
|
code = taos_errno(result);
|
||||||
if (code != 0) {
|
if (code != 0) {
|
||||||
printf("failed to query data from power.meters, ip: %s, reason: %s\n", ip, taos_errstr(result));
|
printf("Failed to query data from power.meters, Server: %s:%hu, ErrCode: 0x%x, ErrMessage: %s\n.", host, port, code, taos_errstr(result));
|
||||||
taos_close(taos);
|
taos_close(taos);
|
||||||
taos_cleanup();
|
taos_cleanup();
|
||||||
return -1;
|
return -1;
|
||||||
|
@ -70,7 +69,6 @@ while ((row = taos_fetch_row(result))) {
|
||||||
}
|
}
|
||||||
printf("total rows: %d\n", rows);
|
printf("total rows: %d\n", rows);
|
||||||
taos_free_result(result);
|
taos_free_result(result);
|
||||||
printf("success to query data from power.meters\n");
|
|
||||||
|
|
||||||
// close & clean
|
// close & clean
|
||||||
taos_close(taos);
|
taos_close(taos);
|
||||||
|
|
|
@ -24,33 +24,41 @@
|
||||||
|
|
||||||
static int DemoSmlInsert() {
|
static int DemoSmlInsert() {
|
||||||
// ANCHOR: schemaless
|
// ANCHOR: schemaless
|
||||||
const char *ip = "localhost";
|
const char *host = "localhost";
|
||||||
const char *user = "root";
|
const char *user = "root";
|
||||||
const char *password = "taosdata";
|
const char *password = "taosdata";
|
||||||
|
uint16_t port = 6030;
|
||||||
|
int code = 0;
|
||||||
|
|
||||||
// connect
|
// connect
|
||||||
TAOS *taos = taos_connect(ip, user, password, NULL, 0);
|
TAOS *taos = taos_connect(host, user, password, NULL, port);
|
||||||
if (taos == NULL) {
|
if (taos == NULL) {
|
||||||
printf("failed to connect to server %s, reason: %s\n", ip, taos_errstr(NULL));
|
printf("Failed to connect to %s:%hu, ErrCode: 0x%x, ErrMessage: %s.\n", host, port, taos_errno(NULL), taos_errstr(NULL));
|
||||||
taos_cleanup();
|
taos_cleanup();
|
||||||
return -1;
|
return -1;
|
||||||
}
|
}
|
||||||
printf("success to connect server %s\n", ip);
|
|
||||||
|
|
||||||
// create database
|
// create database
|
||||||
TAOS_RES *result = taos_query(taos, "CREATE DATABASE IF NOT EXISTS power");
|
TAOS_RES *result = taos_query(taos, "CREATE DATABASE IF NOT EXISTS power");
|
||||||
int code = taos_errno(result);
|
code = taos_errno(result);
|
||||||
if (code != 0) {
|
if (code != 0) {
|
||||||
printf("failed to create database power, reason: %s\n", taos_errstr(result));
|
printf("Failed to create database power, Server: %s:%hu, ErrCode: 0x%x, ErrMessage: %s.\n", host, port, code, taos_errstr(result));
|
||||||
taos_close(taos);
|
taos_close(taos);
|
||||||
taos_cleanup();
|
taos_cleanup();
|
||||||
return -1;
|
return -1;
|
||||||
}
|
}
|
||||||
taos_free_result(result);
|
taos_free_result(result);
|
||||||
printf("success to create database power\n");
|
printf("Create database power successfully.\n");
|
||||||
|
|
||||||
// use database
|
// use database
|
||||||
result = taos_query(taos, "USE power");
|
result = taos_query(taos, "USE power");
|
||||||
|
code = taos_errno(result);
|
||||||
|
if (code != 0) {
|
||||||
|
printf("Failed to execute use power, Server: %s:%hu, ErrCode: 0x%x, ErrMessage: %s\n.", host, port, code, taos_errstr(result));
|
||||||
|
taos_close(taos);
|
||||||
|
taos_cleanup();
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
taos_free_result(result);
|
taos_free_result(result);
|
||||||
|
|
||||||
// schemaless demo data
|
// schemaless demo data
|
||||||
|
@ -61,29 +69,31 @@ char * json_demo = "{\"metric\": \"metric_json\",\"timestamp\": 1626846400,\"val
|
||||||
// influxdb line protocol
|
// influxdb line protocol
|
||||||
char *lines[] = {line_demo};
|
char *lines[] = {line_demo};
|
||||||
result = taos_schemaless_insert(taos, lines, 1, TSDB_SML_LINE_PROTOCOL, TSDB_SML_TIMESTAMP_MILLI_SECONDS);
|
result = taos_schemaless_insert(taos, lines, 1, TSDB_SML_LINE_PROTOCOL, TSDB_SML_TIMESTAMP_MILLI_SECONDS);
|
||||||
if (taos_errno(result) != 0) {
|
code = taos_errno(result);
|
||||||
printf("failed to insert schemaless line data, reason: %s\n", taos_errstr(result));
|
if (code != 0) {
|
||||||
|
printf("Failed to insert schemaless line data, Server: %s:%hu, ErrCode: 0x%x, ErrMessage: %s\n.", host, port, code, taos_errstr(result));
|
||||||
taos_close(taos);
|
taos_close(taos);
|
||||||
taos_cleanup();
|
taos_cleanup();
|
||||||
return -1;
|
return -1;
|
||||||
}
|
}
|
||||||
|
|
||||||
int rows = taos_affected_rows(result);
|
int rows = taos_affected_rows(result);
|
||||||
printf("success to insert %d rows of schemaless line data\n", rows);
|
printf("Insert %d rows of schemaless line data successfully.\n", rows);
|
||||||
taos_free_result(result);
|
taos_free_result(result);
|
||||||
|
|
||||||
// opentsdb telnet protocol
|
// opentsdb telnet protocol
|
||||||
char *telnets[] = {telnet_demo};
|
char *telnets[] = {telnet_demo};
|
||||||
result = taos_schemaless_insert(taos, telnets, 1, TSDB_SML_TELNET_PROTOCOL, TSDB_SML_TIMESTAMP_MILLI_SECONDS);
|
result = taos_schemaless_insert(taos, telnets, 1, TSDB_SML_TELNET_PROTOCOL, TSDB_SML_TIMESTAMP_MILLI_SECONDS);
|
||||||
if (taos_errno(result) != 0) {
|
code = taos_errno(result);
|
||||||
printf("failed to insert schemaless telnet data, reason: %s\n", taos_errstr(result));
|
if (code != 0) {
|
||||||
|
printf("Failed to insert schemaless telnet data, Server: %s:%hu, ErrCode: 0x%x, ErrMessage: %s\n.", host, port, code, taos_errstr(result));
|
||||||
taos_close(taos);
|
taos_close(taos);
|
||||||
taos_cleanup();
|
taos_cleanup();
|
||||||
return -1;
|
return -1;
|
||||||
}
|
}
|
||||||
|
|
||||||
rows = taos_affected_rows(result);
|
rows = taos_affected_rows(result);
|
||||||
printf("success to insert %d rows of schemaless telnet data\n", rows);
|
printf("Insert %d rows of schemaless telnet data successfully.\n", rows);
|
||||||
taos_free_result(result);
|
taos_free_result(result);
|
||||||
|
|
||||||
// opentsdb json protocol
|
// opentsdb json protocol
|
||||||
|
@ -91,16 +101,17 @@ char *jsons[1] = {0};
|
||||||
// allocate memory for json data. can not use static memory.
|
// allocate memory for json data. can not use static memory.
|
||||||
jsons[0] = malloc(1024);
|
jsons[0] = malloc(1024);
|
||||||
if (jsons[0] == NULL) {
|
if (jsons[0] == NULL) {
|
||||||
printf("failed to allocate memory\n");
|
printf("Failed to allocate memory\n");
|
||||||
taos_close(taos);
|
taos_close(taos);
|
||||||
taos_cleanup();
|
taos_cleanup();
|
||||||
return -1;
|
return -1;
|
||||||
}
|
}
|
||||||
(void)strncpy(jsons[0], json_demo, 1023);
|
(void)strncpy(jsons[0], json_demo, 1023);
|
||||||
result = taos_schemaless_insert(taos, jsons, 1, TSDB_SML_JSON_PROTOCOL, TSDB_SML_TIMESTAMP_NOT_CONFIGURED);
|
result = taos_schemaless_insert(taos, jsons, 1, TSDB_SML_JSON_PROTOCOL, TSDB_SML_TIMESTAMP_NOT_CONFIGURED);
|
||||||
if (taos_errno(result) != 0) {
|
code = taos_errno(result);
|
||||||
|
if (code != 0) {
|
||||||
free(jsons[0]);
|
free(jsons[0]);
|
||||||
printf("failed to insert schemaless json data, reason: %s\n", taos_errstr(result));
|
printf("Failed to insert schemaless json data, Server: %s:%hu, ErrCode: 0x%x, ErrMessage: %s\n.", host, port, code, taos_errstr(result));
|
||||||
taos_close(taos);
|
taos_close(taos);
|
||||||
taos_cleanup();
|
taos_cleanup();
|
||||||
return -1;
|
return -1;
|
||||||
|
@ -108,7 +119,7 @@ if (taos_errno(result) != 0) {
|
||||||
free(jsons[0]);
|
free(jsons[0]);
|
||||||
|
|
||||||
rows = taos_affected_rows(result);
|
rows = taos_affected_rows(result);
|
||||||
printf("success to insert %d rows of schemaless json data\n", rows);
|
printf("Insert %d rows of schemaless json data successfully.\n", rows);
|
||||||
taos_free_result(result);
|
taos_free_result(result);
|
||||||
|
|
||||||
// close & clean
|
// close & clean
|
||||||
|
|
|
@ -64,6 +64,7 @@ typedef struct {
|
||||||
|
|
||||||
int num_of_sub_table = 10;
|
int num_of_sub_table = 10;
|
||||||
int num_of_row = 10;
|
int num_of_row = 10;
|
||||||
|
int total_affected = 0;
|
||||||
/**
|
/**
|
||||||
* @brief insert data using stmt API
|
* @brief insert data using stmt API
|
||||||
*
|
*
|
||||||
|
@ -72,10 +73,14 @@ int num_of_row = 10;
|
||||||
void insertData(TAOS *taos) {
|
void insertData(TAOS *taos) {
|
||||||
// init
|
// init
|
||||||
TAOS_STMT *stmt = taos_stmt_init(taos);
|
TAOS_STMT *stmt = taos_stmt_init(taos);
|
||||||
|
if (stmt == NULL) {
|
||||||
|
printf("Failed to init taos_stmt, error: %s\n", taos_stmt_errstr(NULL));
|
||||||
|
exit(EXIT_FAILURE);
|
||||||
|
}
|
||||||
// prepare
|
// prepare
|
||||||
const char *sql = "INSERT INTO ? USING meters TAGS(?,?) VALUES (?,?,?,?)";
|
const char *sql = "INSERT INTO ? USING meters TAGS(?,?) VALUES (?,?,?,?)";
|
||||||
int code = taos_stmt_prepare(stmt, sql, 0);
|
int code = taos_stmt_prepare(stmt, sql, 0);
|
||||||
checkErrorCode(stmt, code, "failed to execute taos_stmt_prepare");
|
checkErrorCode(stmt, code, "Failed to execute taos_stmt_prepare");
|
||||||
for (int i = 1; i <= num_of_sub_table; i++) {
|
for (int i = 1; i <= num_of_sub_table; i++) {
|
||||||
char table_name[20];
|
char table_name[20];
|
||||||
sprintf(table_name, "d_bind_%d", i);
|
sprintf(table_name, "d_bind_%d", i);
|
||||||
|
@ -99,7 +104,7 @@ void insertData(TAOS *taos) {
|
||||||
tags[1].is_null = NULL;
|
tags[1].is_null = NULL;
|
||||||
tags[1].num = 1;
|
tags[1].num = 1;
|
||||||
code = taos_stmt_set_tbname_tags(stmt, table_name, tags);
|
code = taos_stmt_set_tbname_tags(stmt, table_name, tags);
|
||||||
checkErrorCode(stmt, code, "failed to set table name and tags\n");
|
checkErrorCode(stmt, code, "Failed to set table name and tags\n");
|
||||||
|
|
||||||
// insert rows
|
// insert rows
|
||||||
TAOS_MULTI_BIND params[4];
|
TAOS_MULTI_BIND params[4];
|
||||||
|
@ -142,25 +147,31 @@ void insertData(TAOS *taos) {
|
||||||
params[3].buffer = &phase;
|
params[3].buffer = &phase;
|
||||||
// bind param
|
// bind param
|
||||||
code = taos_stmt_bind_param(stmt, params);
|
code = taos_stmt_bind_param(stmt, params);
|
||||||
checkErrorCode(stmt, code, "failed to bind param");
|
checkErrorCode(stmt, code, "Failed to bind param");
|
||||||
}
|
}
|
||||||
// add batch
|
// add batch
|
||||||
code = taos_stmt_add_batch(stmt);
|
code = taos_stmt_add_batch(stmt);
|
||||||
checkErrorCode(stmt, code, "failed to add batch");
|
checkErrorCode(stmt, code, "Failed to add batch");
|
||||||
// execute batch
|
// execute batch
|
||||||
code = taos_stmt_execute(stmt);
|
code = taos_stmt_execute(stmt);
|
||||||
checkErrorCode(stmt, code, "failed to exec stmt");
|
checkErrorCode(stmt, code, "Failed to exec stmt");
|
||||||
// get affected rows
|
// get affected rows
|
||||||
int affected = taos_stmt_affected_rows_once(stmt);
|
int affected = taos_stmt_affected_rows_once(stmt);
|
||||||
printf("table %s insert %d rows.\n", table_name, affected);
|
total_affected += affected;
|
||||||
}
|
}
|
||||||
|
printf("Successfully inserted %d rows to power.meters.\n", total_affected);
|
||||||
taos_stmt_close(stmt);
|
taos_stmt_close(stmt);
|
||||||
}
|
}
|
||||||
|
|
||||||
int main() {
|
int main() {
|
||||||
TAOS *taos = taos_connect("localhost", "root", "taosdata", NULL, 6030);
|
const char *host = "localhost";
|
||||||
|
const char *user = "root";
|
||||||
|
const char *password = "taosdata";
|
||||||
|
uint16_t port = 6030;
|
||||||
|
TAOS *taos = taos_connect(host, user, password, NULL, port);
|
||||||
if (taos == NULL) {
|
if (taos == NULL) {
|
||||||
printf("failed to connect to server\n");
|
printf("Failed to connect to %s:%hu, ErrCode: 0x%x, ErrMessage: %s.\n", host, port, taos_errno(NULL), taos_errstr(NULL));
|
||||||
|
taos_cleanup();
|
||||||
exit(EXIT_FAILURE);
|
exit(EXIT_FAILURE);
|
||||||
}
|
}
|
||||||
// create database and table
|
// create database and table
|
||||||
|
|
|
@ -13,6 +13,8 @@
|
||||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
// to compile: gcc -o tmq_demo tmq_demo.c -ltaos -lpthread
|
||||||
|
|
||||||
#include <assert.h>
|
#include <assert.h>
|
||||||
#include <pthread.h>
|
#include <pthread.h>
|
||||||
#include <stdio.h>
|
#include <stdio.h>
|
||||||
|
@ -26,9 +28,28 @@ volatile int thread_stop = 0;
|
||||||
static int running = 1;
|
static int running = 1;
|
||||||
const char* topic_name = "topic_meters";
|
const char* topic_name = "topic_meters";
|
||||||
|
|
||||||
|
typedef struct {
|
||||||
|
const char* enable_auto_commit;
|
||||||
|
const char* auto_commit_interval_ms;
|
||||||
|
const char* group_id;
|
||||||
|
const char* client_id;
|
||||||
|
const char* td_connect_host;
|
||||||
|
const char* td_connect_port;
|
||||||
|
const char* td_connect_user;
|
||||||
|
const char* td_connect_pass;
|
||||||
|
const char* auto_offset_reset;
|
||||||
|
} ConsumerConfig;
|
||||||
|
|
||||||
void* prepare_data(void* arg) {
|
void* prepare_data(void* arg) {
|
||||||
TAOS* pConn = taos_connect("localhost", "root", "taosdata", NULL, 0);
|
const char *host = "localhost";
|
||||||
|
const char *user = "root";
|
||||||
|
const char *password = "taosdata";
|
||||||
|
uint16_t port = 6030;
|
||||||
|
int code = 0;
|
||||||
|
TAOS *pConn = taos_connect(host, user, password, NULL, port);
|
||||||
if (pConn == NULL) {
|
if (pConn == NULL) {
|
||||||
|
fprintf(stderr, "Failed to connect to %s:%hu, ErrCode: 0x%x, ErrMessage: %s.\n", host, port, taos_errno(NULL), taos_errstr(NULL));
|
||||||
|
taos_cleanup();
|
||||||
return NULL;
|
return NULL;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -45,13 +66,14 @@ void* prepare_data(void* arg) {
|
||||||
i);
|
i);
|
||||||
|
|
||||||
pRes = taos_query(pConn, buf);
|
pRes = taos_query(pConn, buf);
|
||||||
if (taos_errno(pRes) != 0) {
|
code = taos_errno(pRes);
|
||||||
printf("error in insert data to power.meters, reason:%s\n", taos_errstr(pRes));
|
if (code != 0) {
|
||||||
|
fprintf(stderr, "Failed to insert data to power.meters, ErrCode: 0x%x, ErrMessage: %s.\n", code, taos_errstr(pRes));
|
||||||
}
|
}
|
||||||
taos_free_result(pRes);
|
taos_free_result(pRes);
|
||||||
sleep(1);
|
sleep(1);
|
||||||
}
|
}
|
||||||
printf("prepare data thread exit\n");
|
fprintf(stdout, "Prepare data thread exit\n");
|
||||||
return NULL;
|
return NULL;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -63,9 +85,9 @@ static int32_t msg_process(TAOS_RES* msg) {
|
||||||
const char* dbName = tmq_get_db_name(msg);
|
const char* dbName = tmq_get_db_name(msg);
|
||||||
int32_t vgroupId = tmq_get_vgroup_id(msg);
|
int32_t vgroupId = tmq_get_vgroup_id(msg);
|
||||||
|
|
||||||
printf("topic: %s\n", topicName);
|
fprintf(stdout, "topic: %s\n", topicName);
|
||||||
printf("db: %s\n", dbName);
|
fprintf(stdout, "db: %s\n", dbName);
|
||||||
printf("vgroup id: %d\n", vgroupId);
|
fprintf(stdout, "vgroup id: %d\n", vgroupId);
|
||||||
|
|
||||||
while (1) {
|
while (1) {
|
||||||
// get one row data from message
|
// get one row data from message
|
||||||
|
@ -81,11 +103,11 @@ static int32_t msg_process(TAOS_RES* msg) {
|
||||||
rows++;
|
rows++;
|
||||||
// print the row content
|
// print the row content
|
||||||
if (taos_print_row(buf, row, fields, numOfFields) < 0) {
|
if (taos_print_row(buf, row, fields, numOfFields) < 0) {
|
||||||
printf("failed to print row\n");
|
fprintf(stderr, "Failed to print row\n");
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
// print the precision and row content to the console
|
// print the precision and row content to the console
|
||||||
printf("precision: %d, row content: %s\n", precision, buf);
|
fprintf(stdout, "precision: %d, data: %s\n", precision, buf);
|
||||||
}
|
}
|
||||||
|
|
||||||
return rows;
|
return rows;
|
||||||
|
@ -93,42 +115,53 @@ static int32_t msg_process(TAOS_RES* msg) {
|
||||||
// ANCHOR_END: msg_process
|
// ANCHOR_END: msg_process
|
||||||
|
|
||||||
static int32_t init_env() {
|
static int32_t init_env() {
|
||||||
TAOS* pConn = taos_connect("localhost", "root", "taosdata", NULL, 0);
|
const char *host = "localhost";
|
||||||
|
const char *user = "root";
|
||||||
|
const char *password = "taosdata";
|
||||||
|
uint16_t port = 6030;
|
||||||
|
int code = 0;
|
||||||
|
TAOS *pConn = taos_connect(host, user, password, NULL, port);
|
||||||
if (pConn == NULL) {
|
if (pConn == NULL) {
|
||||||
|
fprintf(stderr, "Failed to connect to %s:%hu, ErrCode: 0x%x, ErrMessage: %s.\n", host, port, taos_errno(NULL), taos_errstr(NULL));
|
||||||
|
taos_cleanup();
|
||||||
return -1;
|
return -1;
|
||||||
}
|
}
|
||||||
|
|
||||||
TAOS_RES* pRes;
|
TAOS_RES* pRes;
|
||||||
// drop database if exists
|
// drop database if exists
|
||||||
printf("create database\n");
|
fprintf(stdout, "Create database.\n");
|
||||||
pRes = taos_query(pConn, "drop topic if exists topic_meters");
|
pRes = taos_query(pConn, "DROP TOPIC IF EXISTS topic_meters");
|
||||||
if (taos_errno(pRes) != 0) {
|
code = taos_errno(pRes);
|
||||||
printf("error in drop topic_meters, reason:%s\n", taos_errstr(pRes));
|
if (code != 0) {
|
||||||
|
fprintf(stderr, "Failed to drop topic_meters, ErrCode: 0x%x, ErrMessage: %s.\n", code, taos_errstr(pRes));
|
||||||
}
|
}
|
||||||
taos_free_result(pRes);
|
taos_free_result(pRes);
|
||||||
|
|
||||||
pRes = taos_query(pConn, "drop database if exists power");
|
pRes = taos_query(pConn, "DROP DATABASE IF EXISTS power");
|
||||||
if (taos_errno(pRes) != 0) {
|
code = taos_errno(pRes);
|
||||||
printf("error in drop power, reason:%s\n", taos_errstr(pRes));
|
if (code != 0) {
|
||||||
|
fprintf(stderr, "Failed to drop database power, ErrCode: 0x%x, ErrMessage: %s.\n", code, taos_errstr(pRes));
|
||||||
}
|
}
|
||||||
taos_free_result(pRes);
|
taos_free_result(pRes);
|
||||||
|
|
||||||
// create database
|
// create database
|
||||||
pRes = taos_query(pConn, "create database power precision 'ms' WAL_RETENTION_PERIOD 3600");
|
pRes = taos_query(pConn, "CREATE DATABASE power PRECISION 'ms' WAL_RETENTION_PERIOD 3600");
|
||||||
if (taos_errno(pRes) != 0) {
|
code = taos_errno(pRes);
|
||||||
printf("error in create tmqdb, reason:%s\n", taos_errstr(pRes));
|
if (code != 0) {
|
||||||
|
fprintf(stderr, "Failed to create tmqdb, ErrCode: 0x%x, ErrMessage: %s.\n", code, taos_errstr(pRes));
|
||||||
goto END;
|
goto END;
|
||||||
}
|
}
|
||||||
taos_free_result(pRes);
|
taos_free_result(pRes);
|
||||||
|
|
||||||
// create super table
|
// create super table
|
||||||
printf("create super table\n");
|
fprintf(stdout, "Create super table.\n");
|
||||||
pRes = taos_query(
|
pRes = taos_query(
|
||||||
pConn,
|
pConn,
|
||||||
"CREATE STABLE IF NOT EXISTS power.meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS "
|
"CREATE STABLE IF NOT EXISTS power.meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS "
|
||||||
"(groupId INT, location BINARY(24))");
|
"(groupId INT, location BINARY(24))");
|
||||||
if (taos_errno(pRes) != 0) {
|
code = taos_errno(pRes);
|
||||||
printf("failed to create super table meters, reason:%s\n", taos_errstr(pRes));
|
if (code != 0) {
|
||||||
|
fprintf(stderr, "Failed to create super table meters, ErrCode: 0x%x, ErrMessage: %s.\n", code, taos_errstr(pRes));
|
||||||
goto END;
|
goto END;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -143,16 +176,24 @@ END:
|
||||||
}
|
}
|
||||||
|
|
||||||
int32_t create_topic() {
|
int32_t create_topic() {
|
||||||
printf("create topic\n");
|
fprintf(stdout, "Create topic.\n");
|
||||||
TAOS_RES* pRes;
|
TAOS_RES* pRes;
|
||||||
TAOS* pConn = taos_connect("localhost", "root", "taosdata", NULL, 0);
|
const char *host = "localhost";
|
||||||
|
const char *user = "root";
|
||||||
|
const char *password = "taosdata";
|
||||||
|
uint16_t port = 6030;
|
||||||
|
int code = 0;
|
||||||
|
TAOS *pConn = taos_connect(host, user, password, NULL, port);
|
||||||
if (pConn == NULL) {
|
if (pConn == NULL) {
|
||||||
|
fprintf(stderr, "Failed to connect to %s:%hu, ErrCode: 0x%x, ErrMessage: %s.\n", host, port, taos_errno(NULL), taos_errstr(NULL));
|
||||||
|
taos_cleanup();
|
||||||
return -1;
|
return -1;
|
||||||
}
|
}
|
||||||
|
|
||||||
pRes = taos_query(pConn, "use power");
|
pRes = taos_query(pConn, "USE POWER");
|
||||||
|
code = taos_errno(pRes);
|
||||||
if (taos_errno(pRes) != 0) {
|
if (taos_errno(pRes) != 0) {
|
||||||
printf("error in use tmqdb, reason:%s\n", taos_errstr(pRes));
|
fprintf(stderr, "Failed to use tmqdb, ErrCode: 0x%x, ErrMessage: %s.\n", code, taos_errstr(pRes));
|
||||||
return -1;
|
return -1;
|
||||||
}
|
}
|
||||||
taos_free_result(pRes);
|
taos_free_result(pRes);
|
||||||
|
@ -160,8 +201,9 @@ int32_t create_topic() {
|
||||||
pRes = taos_query(
|
pRes = taos_query(
|
||||||
pConn,
|
pConn,
|
||||||
"CREATE TOPIC IF NOT EXISTS topic_meters AS SELECT ts, current, voltage, phase, groupid, location FROM meters");
|
"CREATE TOPIC IF NOT EXISTS topic_meters AS SELECT ts, current, voltage, phase, groupid, location FROM meters");
|
||||||
if (taos_errno(pRes) != 0) {
|
code = taos_errno(pRes);
|
||||||
printf("failed to create topic topic_meters, reason:%s\n", taos_errstr(pRes));
|
if (code != 0) {
|
||||||
|
fprintf(stderr, "Failed to create topic topic_meters, ErrCode: 0x%x, ErrMessage: %s.\n", code, taos_errstr(pRes));
|
||||||
return -1;
|
return -1;
|
||||||
}
|
}
|
||||||
taos_free_result(pRes);
|
taos_free_result(pRes);
|
||||||
|
@ -171,11 +213,11 @@ int32_t create_topic() {
|
||||||
}
|
}
|
||||||
|
|
||||||
void tmq_commit_cb_print(tmq_t* tmq, int32_t code, void* param) {
|
void tmq_commit_cb_print(tmq_t* tmq, int32_t code, void* param) {
|
||||||
printf("tmq_commit_cb_print() code: %d, tmq: %p, param: %p\n", code, tmq, param);
|
fprintf(stdout, "tmq_commit_cb_print() code: %d, tmq: %p, param: %p\n", code, tmq, param);
|
||||||
}
|
}
|
||||||
|
|
||||||
// ANCHOR: create_consumer_1
|
// ANCHOR: create_consumer_1
|
||||||
tmq_t* build_consumer() {
|
tmq_t* build_consumer(const ConsumerConfig* config) {
|
||||||
tmq_conf_res_t code;
|
tmq_conf_res_t code;
|
||||||
tmq_t* tmq = NULL;
|
tmq_t* tmq = NULL;
|
||||||
|
|
||||||
|
@ -183,37 +225,47 @@ tmq_t* build_consumer() {
|
||||||
tmq_conf_t* conf = tmq_conf_new();
|
tmq_conf_t* conf = tmq_conf_new();
|
||||||
|
|
||||||
// set the configuration parameters
|
// set the configuration parameters
|
||||||
code = tmq_conf_set(conf, "enable.auto.commit", "true");
|
code = tmq_conf_set(conf, "enable.auto.commit", config->enable_auto_commit);
|
||||||
if (TMQ_CONF_OK != code) {
|
if (TMQ_CONF_OK != code) {
|
||||||
tmq_conf_destroy(conf);
|
tmq_conf_destroy(conf);
|
||||||
return NULL;
|
return NULL;
|
||||||
}
|
}
|
||||||
code = tmq_conf_set(conf, "auto.commit.interval.ms", "1000");
|
code = tmq_conf_set(conf, "auto.commit.interval.ms", config->auto_commit_interval_ms);
|
||||||
if (TMQ_CONF_OK != code) {
|
if (TMQ_CONF_OK != code) {
|
||||||
tmq_conf_destroy(conf);
|
tmq_conf_destroy(conf);
|
||||||
return NULL;
|
return NULL;
|
||||||
}
|
}
|
||||||
code = tmq_conf_set(conf, "group.id", "group1");
|
code = tmq_conf_set(conf, "group.id", config->group_id);
|
||||||
if (TMQ_CONF_OK != code) {
|
if (TMQ_CONF_OK != code) {
|
||||||
tmq_conf_destroy(conf);
|
tmq_conf_destroy(conf);
|
||||||
return NULL;
|
return NULL;
|
||||||
}
|
}
|
||||||
code = tmq_conf_set(conf, "client.id", "client1");
|
code = tmq_conf_set(conf, "client.id", config->client_id);
|
||||||
if (TMQ_CONF_OK != code) {
|
if (TMQ_CONF_OK != code) {
|
||||||
tmq_conf_destroy(conf);
|
tmq_conf_destroy(conf);
|
||||||
return NULL;
|
return NULL;
|
||||||
}
|
}
|
||||||
code = tmq_conf_set(conf, "td.connect.user", "root");
|
code = tmq_conf_set(conf, "td.connect.ip", config->td_connect_host);
|
||||||
if (TMQ_CONF_OK != code) {
|
if (TMQ_CONF_OK != code) {
|
||||||
tmq_conf_destroy(conf);
|
tmq_conf_destroy(conf);
|
||||||
return NULL;
|
return NULL;
|
||||||
}
|
}
|
||||||
code = tmq_conf_set(conf, "td.connect.pass", "taosdata");
|
code = tmq_conf_set(conf, "td.connect.port", config->td_connect_port);
|
||||||
if (TMQ_CONF_OK != code) {
|
if (TMQ_CONF_OK != code) {
|
||||||
tmq_conf_destroy(conf);
|
tmq_conf_destroy(conf);
|
||||||
return NULL;
|
return NULL;
|
||||||
}
|
}
|
||||||
code = tmq_conf_set(conf, "auto.offset.reset", "latest");
|
code = tmq_conf_set(conf, "td.connect.user", config->td_connect_user);
|
||||||
|
if (TMQ_CONF_OK != code) {
|
||||||
|
tmq_conf_destroy(conf);
|
||||||
|
return NULL;
|
||||||
|
}
|
||||||
|
code = tmq_conf_set(conf, "td.connect.pass", config->td_connect_pass);
|
||||||
|
if (TMQ_CONF_OK != code) {
|
||||||
|
tmq_conf_destroy(conf);
|
||||||
|
return NULL;
|
||||||
|
}
|
||||||
|
code = tmq_conf_set(conf, "auto.offset.reset", config->auto_offset_reset);
|
||||||
if (TMQ_CONF_OK != code) {
|
if (TMQ_CONF_OK != code) {
|
||||||
tmq_conf_destroy(conf);
|
tmq_conf_destroy(conf);
|
||||||
return NULL;
|
return NULL;
|
||||||
|
@ -243,6 +295,7 @@ tmq_list_t* build_topic_list() {
|
||||||
if (code) {
|
if (code) {
|
||||||
// if failed, destroy the list and return NULL
|
// if failed, destroy the list and return NULL
|
||||||
tmq_list_destroy(topicList);
|
tmq_list_destroy(topicList);
|
||||||
|
fprintf(stderr, "Failed to create topic_list, ErrCode: 0x%x, ErrMessage: %s.\n", code, tmq_err2str(code));
|
||||||
return NULL;
|
return NULL;
|
||||||
}
|
}
|
||||||
// if success, return the list
|
// if success, return the list
|
||||||
|
@ -285,7 +338,7 @@ void consume_repeatly(tmq_t* tmq) {
|
||||||
// get the topic assignment
|
// get the topic assignment
|
||||||
int32_t code = tmq_get_topic_assignment(tmq, topic_name, &pAssign, &numOfAssignment);
|
int32_t code = tmq_get_topic_assignment(tmq, topic_name, &pAssign, &numOfAssignment);
|
||||||
if (code != 0 || pAssign == NULL || numOfAssignment == 0) {
|
if (code != 0 || pAssign == NULL || numOfAssignment == 0) {
|
||||||
fprintf(stderr, "failed to get assignment, reason:%s", tmq_err2str(code));
|
fprintf(stderr, "Failed to get assignment, ErrCode: 0x%x, ErrMessage: %s.\n", code, tmq_err2str(code));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -295,7 +348,9 @@ void consume_repeatly(tmq_t* tmq) {
|
||||||
|
|
||||||
code = tmq_offset_seek(tmq, topic_name, p->vgId, p->begin);
|
code = tmq_offset_seek(tmq, topic_name, p->vgId, p->begin);
|
||||||
if (code != 0) {
|
if (code != 0) {
|
||||||
fprintf(stderr, "failed to seek to %d, reason:%s", (int)p->begin, tmq_err2str(code));
|
fprintf(stderr, "Failed to seek assignment %d to beginning %ld, ErrCode: 0x%x, ErrMessage: %s.\n", i, p->begin, code, tmq_err2str(code));
|
||||||
|
} else {
|
||||||
|
fprintf(stdout, "Seek assignment %d to beginning %ld successfully.\n", i, p->begin);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -324,10 +379,12 @@ void manual_commit(tmq_t* tmq) {
|
||||||
int32_t code = tmq_commit_sync(tmq, tmqmsg);
|
int32_t code = tmq_commit_sync(tmq, tmqmsg);
|
||||||
|
|
||||||
if (code) {
|
if (code) {
|
||||||
fprintf(stderr, "Failed to commit message: %s\n", tmq_err2str(code));
|
fprintf(stderr, "Failed to commit message, ErrCode: 0x%x, ErrMessage: %s.\n", code, tmq_err2str(code));
|
||||||
// free the message
|
// free the message
|
||||||
taos_free_result(tmqmsg);
|
taos_free_result(tmqmsg);
|
||||||
break;
|
break;
|
||||||
|
} else {
|
||||||
|
fprintf(stdout, "Commit offset manually successfully.\n");
|
||||||
}
|
}
|
||||||
// free the message
|
// free the message
|
||||||
taos_free_result(tmqmsg);
|
taos_free_result(tmqmsg);
|
||||||
|
@ -339,7 +396,7 @@ void manual_commit(tmq_t* tmq) {
|
||||||
}
|
}
|
||||||
|
|
||||||
// print the result: total messages and total rows consumed
|
// print the result: total messages and total rows consumed
|
||||||
fprintf(stderr, "%d msg consumed, include %d rows\n", msgCnt, totalRows);
|
fprintf(stderr, "%d msg consumed, include %d rows.\n", msgCnt, totalRows);
|
||||||
}
|
}
|
||||||
// ANCHOR_END: manual_commit
|
// ANCHOR_END: manual_commit
|
||||||
|
|
||||||
|
@ -356,28 +413,44 @@ int main(int argc, char* argv[]) {
|
||||||
}
|
}
|
||||||
|
|
||||||
if (pthread_create(&thread_id, NULL, &prepare_data, NULL)) {
|
if (pthread_create(&thread_id, NULL, &prepare_data, NULL)) {
|
||||||
fprintf(stderr, "create thread failed\n");
|
fprintf(stderr, "Failed to create thread.\n");
|
||||||
return 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
// ANCHOR: create_consumer_2
|
|
||||||
tmq_t* tmq = build_consumer();
|
|
||||||
if (NULL == tmq) {
|
|
||||||
fprintf(stderr, "build consumer to localhost fail!\n");
|
|
||||||
return -1;
|
return -1;
|
||||||
}
|
}
|
||||||
printf("build consumer to localhost successfully \n");
|
|
||||||
|
ConsumerConfig config = {
|
||||||
|
.enable_auto_commit = "true",
|
||||||
|
.auto_commit_interval_ms = "1000",
|
||||||
|
.group_id = "group1",
|
||||||
|
.client_id = "client1",
|
||||||
|
.td_connect_host = "localhost",
|
||||||
|
.td_connect_port = "6030",
|
||||||
|
.td_connect_user = "root",
|
||||||
|
.td_connect_pass = "taosdata",
|
||||||
|
.auto_offset_reset = "latest"
|
||||||
|
};
|
||||||
|
|
||||||
|
// ANCHOR: create_consumer_2
|
||||||
|
tmq_t* tmq = build_consumer(&config);
|
||||||
|
if (NULL == tmq) {
|
||||||
|
fprintf(stderr, "Failed to create native consumer, host: %s, groupId: %s, , clientId: %s.\n", config.td_connect_host, config.group_id, config.client_id);
|
||||||
|
return -1;
|
||||||
|
} else {
|
||||||
|
fprintf(stdout, "Create consumer successfully, host: %s, groupId: %s, , clientId: %s.\n", config.td_connect_host, config.group_id, config.client_id);
|
||||||
|
}
|
||||||
|
|
||||||
// ANCHOR_END: create_consumer_2
|
// ANCHOR_END: create_consumer_2
|
||||||
|
|
||||||
// ANCHOR: subscribe_3
|
// ANCHOR: subscribe_3
|
||||||
tmq_list_t* topic_list = build_topic_list();
|
tmq_list_t* topic_list = build_topic_list();
|
||||||
if (NULL == topic_list) {
|
if (NULL == topic_list) {
|
||||||
|
fprintf(stderr, "Failed to create topic_list.\n");
|
||||||
return -1;
|
return -1;
|
||||||
}
|
}
|
||||||
|
|
||||||
if ((code = tmq_subscribe(tmq, topic_list))) {
|
if ((code = tmq_subscribe(tmq, topic_list))) {
|
||||||
fprintf(stderr, "Failed to tmq_subscribe(): %s\n", tmq_err2str(code));
|
fprintf(stderr, "Failed to subscribe topic_list, ErrCode: 0x%x, ErrMessage: %s.\n", code, tmq_err2str(code));
|
||||||
|
} else {
|
||||||
|
fprintf(stdout, "Subscribe topics successfully.\n");
|
||||||
}
|
}
|
||||||
|
|
||||||
tmq_list_destroy(topic_list);
|
tmq_list_destroy(topic_list);
|
||||||
|
@ -393,13 +466,15 @@ int main(int argc, char* argv[]) {
|
||||||
// unsubscribe the topic
|
// unsubscribe the topic
|
||||||
code = tmq_unsubscribe(tmq);
|
code = tmq_unsubscribe(tmq);
|
||||||
if (code) {
|
if (code) {
|
||||||
fprintf(stderr, "Failed to tmq_unsubscribe(): %s\n", tmq_err2str(code));
|
fprintf(stderr, "Failed to unsubscribe consumer, ErrCode: 0x%x, ErrMessage: %s.\n", code, tmq_err2str(code));
|
||||||
|
} else {
|
||||||
|
fprintf(stderr, "Consumer unsubscribed successfully.\n");
|
||||||
}
|
}
|
||||||
fprintf(stderr, "Unsubscribed consumer successfully.\n");
|
|
||||||
// close the consumer
|
// close the consumer
|
||||||
code = tmq_consumer_close(tmq);
|
code = tmq_consumer_close(tmq);
|
||||||
if (code) {
|
if (code) {
|
||||||
fprintf(stderr, "Failed to close consumer: %s\n", tmq_err2str(code));
|
fprintf(stderr, "Failed to close consumer: %s.\n", tmq_err2str(code));
|
||||||
} else {
|
} else {
|
||||||
fprintf(stderr, "Consumer closed successfully.\n");
|
fprintf(stderr, "Consumer closed successfully.\n");
|
||||||
}
|
}
|
||||||
|
|
|
@ -23,55 +23,59 @@
|
||||||
#include "taos.h"
|
#include "taos.h"
|
||||||
|
|
||||||
static int DemoWithReqId() {
|
static int DemoWithReqId() {
|
||||||
// ANCHOR: with_reqid
|
// ANCHOR: with_reqid
|
||||||
const char *ip = "localhost";
|
const char *host = "localhost";
|
||||||
const char *user = "root";
|
const char *user = "root";
|
||||||
const char *password = "taosdata";
|
const char *password = "taosdata";
|
||||||
|
uint16_t port = 6030;
|
||||||
|
int code = 0;
|
||||||
|
|
||||||
// connect
|
// connect
|
||||||
TAOS *taos = taos_connect(ip, user, password, NULL, 0);
|
TAOS *taos = taos_connect(host, user, password, NULL, port);
|
||||||
if (taos == NULL) {
|
if (taos == NULL) {
|
||||||
printf("failed to connect to server %s, reason: %s\n", ip, taos_errstr(NULL));
|
printf("Failed to connect to %s:%hu, ErrCode: 0x%x, ErrMessage: %s.\n", host, port, taos_errno(NULL), taos_errstr(NULL));
|
||||||
taos_cleanup();
|
|
||||||
return -1;
|
|
||||||
}
|
|
||||||
printf("success to connect server %s\n", ip);
|
|
||||||
|
|
||||||
const char *sql = "SELECT ts, current, location FROM power.meters limit 1";
|
|
||||||
// query data with reqid
|
|
||||||
TAOS_RES *result = taos_query_with_reqid(taos, sql, 3L);
|
|
||||||
int code = taos_errno(result);
|
|
||||||
if (code != 0) {
|
|
||||||
printf("failed to query data from power.meters, ip: %s, reason: %s\n", ip, taos_errstr(result));
|
|
||||||
taos_close(taos);
|
|
||||||
taos_cleanup();
|
|
||||||
return -1;
|
|
||||||
}
|
|
||||||
|
|
||||||
TAOS_ROW row = NULL;
|
|
||||||
int rows = 0;
|
|
||||||
int num_fields = taos_field_count(result);
|
|
||||||
TAOS_FIELD *fields = taos_fetch_fields(result);
|
|
||||||
|
|
||||||
printf("fields: %d\n", num_fields);
|
|
||||||
printf("sql: %s, result:\n", sql);
|
|
||||||
|
|
||||||
// fetch the records row by row
|
|
||||||
while ((row = taos_fetch_row(result))) {
|
|
||||||
char temp[1024] = {0};
|
|
||||||
rows++;
|
|
||||||
taos_print_row(temp, row, fields, num_fields);
|
|
||||||
printf("%s\n", temp);
|
|
||||||
}
|
|
||||||
printf("total rows: %d\n", rows);
|
|
||||||
taos_free_result(result);
|
|
||||||
printf("success to query data from power.meters\n");
|
|
||||||
|
|
||||||
// close & clean
|
|
||||||
taos_close(taos);
|
|
||||||
taos_cleanup();
|
taos_cleanup();
|
||||||
return 0;
|
return -1;
|
||||||
// ANCHOR_END: with_reqid
|
}
|
||||||
|
|
||||||
|
const char *sql = "SELECT ts, current, location FROM power.meters limit 1";
|
||||||
|
// query data with reqid
|
||||||
|
long reqid = 3L;
|
||||||
|
TAOS_RES *result = taos_query_with_reqid(taos, sql, reqid);
|
||||||
|
code = taos_errno(result);
|
||||||
|
if (code != 0) {
|
||||||
|
printf("Failed to execute sql with reqId: %ld, Server: %s:%hu, ErrCode: 0x%x, ErrMessage: %s\n.", reqid, host, port, code, taos_errstr(result));
|
||||||
|
taos_close(taos);
|
||||||
|
taos_cleanup();
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
TAOS_ROW row = NULL;
|
||||||
|
int rows = 0;
|
||||||
|
int num_fields = taos_field_count(result);
|
||||||
|
TAOS_FIELD *fields = taos_fetch_fields(result);
|
||||||
|
|
||||||
|
printf("fields: %d\n", num_fields);
|
||||||
|
printf("sql: %s, result:\n", sql);
|
||||||
|
|
||||||
|
// fetch the records row by row
|
||||||
|
while ((row = taos_fetch_row(result))) {
|
||||||
|
char temp[1024] = {0};
|
||||||
|
rows++;
|
||||||
|
taos_print_row(temp, row, fields, num_fields);
|
||||||
|
printf("%s\n", temp);
|
||||||
|
}
|
||||||
|
printf("total rows: %d\n", rows);
|
||||||
|
taos_free_result(result);
|
||||||
|
|
||||||
|
// close & clean
|
||||||
|
taos_close(taos);
|
||||||
|
taos_cleanup();
|
||||||
|
return 0;
|
||||||
|
// ANCHOR_END: with_reqid
|
||||||
|
}
|
||||||
|
|
||||||
|
int main(int argc, char *argv[]) {
|
||||||
|
return DemoWithReqId();
|
||||||
}
|
}
|
||||||
|
|
||||||
int main(int argc, char *argv[]) { return DemoWithReqId(); }
|
|
||||||
|
|
|
@ -5,9 +5,9 @@ namespace TDengineExample
|
||||||
{
|
{
|
||||||
internal class OptsJsonExample
|
internal class OptsJsonExample
|
||||||
{
|
{
|
||||||
|
// ANCHOR: main
|
||||||
public static void Main(string[] args)
|
public static void Main(string[] args)
|
||||||
{
|
{
|
||||||
// ANCHOR: main
|
|
||||||
var host = "127.0.0.1";
|
var host = "127.0.0.1";
|
||||||
|
|
||||||
var lineDemo =
|
var lineDemo =
|
||||||
|
@ -38,20 +38,22 @@ namespace TDengineExample
|
||||||
client.SchemalessInsert(new []{jsonDemo}, TDengineSchemalessProtocol.TSDB_SML_JSON_PROTOCOL,
|
client.SchemalessInsert(new []{jsonDemo}, TDengineSchemalessProtocol.TSDB_SML_JSON_PROTOCOL,
|
||||||
TDengineSchemalessPrecision.TSDB_SML_TIMESTAMP_NOT_CONFIGURED, 0, ReqId.GetReqId());
|
TDengineSchemalessPrecision.TSDB_SML_TIMESTAMP_NOT_CONFIGURED, 0, ReqId.GetReqId());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Console.WriteLine("Inserted data with schemaless successfully.");
|
||||||
}
|
}
|
||||||
catch (TDengineError e)
|
catch (TDengineError e)
|
||||||
{
|
{
|
||||||
// handle TDengine error
|
// handle TDengine error
|
||||||
Console.WriteLine("Failed to insert data with schemaless; ErrCode:" + e.Code + "; ErrMessage: " + e.Error);
|
Console.WriteLine("Failed to insert data with schemaless, host:" + host + "; ErrCode:" + e.Code + "; ErrMessage: " + e.Error);
|
||||||
throw;
|
throw;
|
||||||
}
|
}
|
||||||
catch (Exception e)
|
catch (Exception e)
|
||||||
{
|
{
|
||||||
// handle other exceptions
|
// handle other exceptions
|
||||||
Console.WriteLine("Failed to insert data with schemaless; Err:" + e.Message);
|
Console.WriteLine("Failed to insert data with schemaless, host:" + host + "; ErrMessage: " + e.Message);
|
||||||
throw;
|
throw;
|
||||||
}
|
}
|
||||||
// ANCHOR_END: main
|
|
||||||
}
|
}
|
||||||
|
// ANCHOR_END: main
|
||||||
}
|
}
|
||||||
}
|
}
|
|
@ -12,9 +12,10 @@ namespace TDengineExample
|
||||||
var numOfSubTable = 10;
|
var numOfSubTable = 10;
|
||||||
var numOfRow = 10;
|
var numOfRow = 10;
|
||||||
var random = new Random();
|
var random = new Random();
|
||||||
|
var connectionString = $"host={host};port=6030;username=root;password=taosdata";
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
var builder = new ConnectionStringBuilder($"host={host};port=6030;username=root;password=taosdata");
|
var builder = new ConnectionStringBuilder(connectionString);
|
||||||
using (var client = DbDriver.Open(builder))
|
using (var client = DbDriver.Open(builder))
|
||||||
{
|
{
|
||||||
// create database
|
// create database
|
||||||
|
@ -53,7 +54,7 @@ namespace TDengineExample
|
||||||
stmt.Exec();
|
stmt.Exec();
|
||||||
// get affected rows
|
// get affected rows
|
||||||
var affectedRows = stmt.Affected();
|
var affectedRows = stmt.Affected();
|
||||||
Console.WriteLine($"table {tableName} insert {affectedRows} rows.");
|
Console.WriteLine($"Successfully inserted {affectedRows} rows to {tableName}.");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -61,13 +62,13 @@ namespace TDengineExample
|
||||||
catch (TDengineError e)
|
catch (TDengineError e)
|
||||||
{
|
{
|
||||||
// handle TDengine error
|
// handle TDengine error
|
||||||
Console.WriteLine("Failed to insert to table meters using stmt; ErrCode:" + e.Code + "; ErrMessage: " + e.Error);
|
Console.WriteLine("Failed to insert to table meters using stmt, url: " + connectionString + "; ErrCode:" + e.Code + "; ErrMessage: " + e.Error);
|
||||||
throw;
|
throw;
|
||||||
}
|
}
|
||||||
catch (Exception e)
|
catch (Exception e)
|
||||||
{
|
{
|
||||||
// handle other exceptions
|
// handle other exceptions
|
||||||
Console.WriteLine("Failed to insert to table meters using stmt; Err:" + e.Message);
|
Console.WriteLine("Failed to insert to table meters using stmt, url: " + connectionString + "; ErrMessage: " + e.Message);
|
||||||
throw;
|
throw;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -64,6 +64,9 @@ namespace TMQExample
|
||||||
{
|
{
|
||||||
// ANCHOR: create_consumer
|
// ANCHOR: create_consumer
|
||||||
// consumer config
|
// consumer config
|
||||||
|
var host = "127.0.0.1";
|
||||||
|
var groupId = "group1";
|
||||||
|
var clientId = "client1";
|
||||||
var cfg = new Dictionary<string, string>()
|
var cfg = new Dictionary<string, string>()
|
||||||
{
|
{
|
||||||
{ "td.connect.port", "6030" },
|
{ "td.connect.port", "6030" },
|
||||||
|
@ -71,9 +74,9 @@ namespace TMQExample
|
||||||
{ "msg.with.table.name", "true" },
|
{ "msg.with.table.name", "true" },
|
||||||
{ "enable.auto.commit", "true" },
|
{ "enable.auto.commit", "true" },
|
||||||
{ "auto.commit.interval.ms", "1000" },
|
{ "auto.commit.interval.ms", "1000" },
|
||||||
{ "group.id", "group1" },
|
{ "group.id", groupId },
|
||||||
{ "client.id", "client1" },
|
{ "client.id", clientId },
|
||||||
{ "td.connect.ip", "127.0.0.1" },
|
{ "td.connect.ip", host },
|
||||||
{ "td.connect.user", "root" },
|
{ "td.connect.user", "root" },
|
||||||
{ "td.connect.pass", "taosdata" },
|
{ "td.connect.pass", "taosdata" },
|
||||||
};
|
};
|
||||||
|
@ -82,17 +85,20 @@ namespace TMQExample
|
||||||
{
|
{
|
||||||
// create consumer
|
// create consumer
|
||||||
consumer = new ConsumerBuilder<Dictionary<string, object>>(cfg).Build();
|
consumer = new ConsumerBuilder<Dictionary<string, object>>(cfg).Build();
|
||||||
|
Console.WriteLine("Create consumer successfully, host: " + host + ", groupId: " + groupId +
|
||||||
|
", clientId: " + clientId);
|
||||||
}
|
}
|
||||||
catch (TDengineError e)
|
catch (TDengineError e)
|
||||||
{
|
{
|
||||||
// handle TDengine error
|
// handle TDengine error
|
||||||
Console.WriteLine("Failed to create consumer; ErrCode:" + e.Code + "; ErrMessage: " + e.Error);
|
Console.WriteLine("Failed to create native consumer, host : " + host + "; ErrCode:" + e.Code +
|
||||||
|
"; ErrMessage: " + e.Error);
|
||||||
throw;
|
throw;
|
||||||
}
|
}
|
||||||
catch (Exception e)
|
catch (Exception e)
|
||||||
{
|
{
|
||||||
// handle other exceptions
|
// handle other exceptions
|
||||||
Console.WriteLine("Failed to create consumer; Err:" + e.Message);
|
Console.WriteLine("Failed to create native consumer, host : " + host + "; ErrMessage: " + e.Message);
|
||||||
throw;
|
throw;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -107,6 +113,7 @@ namespace TMQExample
|
||||||
{
|
{
|
||||||
// subscribe
|
// subscribe
|
||||||
consumer.Subscribe(new List<string>() { "topic_meters" });
|
consumer.Subscribe(new List<string>() { "topic_meters" });
|
||||||
|
Console.WriteLine("subscribe topics successfully");
|
||||||
for (int i = 0; i < 50; i++)
|
for (int i = 0; i < 50; i++)
|
||||||
{
|
{
|
||||||
// consume message with using block to ensure the result is disposed
|
// consume message with using block to ensure the result is disposed
|
||||||
|
@ -117,7 +124,7 @@ namespace TMQExample
|
||||||
{
|
{
|
||||||
// handle message
|
// handle message
|
||||||
Console.WriteLine(
|
Console.WriteLine(
|
||||||
$"data {{{((DateTime)message.Value["ts"]).ToString("yyyy-MM-dd HH:mm:ss.fff")}, " +
|
$"data: {{{((DateTime)message.Value["ts"]).ToString("yyyy-MM-dd HH:mm:ss.fff")}, " +
|
||||||
$"{message.Value["current"]}, {message.Value["voltage"]}, {message.Value["phase"]}}}");
|
$"{message.Value["current"]}, {message.Value["voltage"]}, {message.Value["phase"]}}}");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -132,7 +139,7 @@ namespace TMQExample
|
||||||
catch (Exception e)
|
catch (Exception e)
|
||||||
{
|
{
|
||||||
// handle other exceptions
|
// handle other exceptions
|
||||||
Console.WriteLine("Failed to poll data; Err:" + e.Message);
|
Console.WriteLine("Failed to poll data; ErrMessage:" + e.Message);
|
||||||
throw;
|
throw;
|
||||||
}
|
}
|
||||||
// ANCHOR_END: subscribe
|
// ANCHOR_END: subscribe
|
||||||
|
@ -145,40 +152,24 @@ namespace TMQExample
|
||||||
{
|
{
|
||||||
// get assignment
|
// get assignment
|
||||||
var assignment = consumer.Assignment;
|
var assignment = consumer.Assignment;
|
||||||
|
Console.WriteLine($"now assignment: {assignment}");
|
||||||
// seek to the beginning
|
// seek to the beginning
|
||||||
foreach (var topicPartition in assignment)
|
foreach (var topicPartition in assignment)
|
||||||
{
|
{
|
||||||
consumer.Seek(new TopicPartitionOffset(topicPartition.Topic, topicPartition.Partition, 0));
|
consumer.Seek(new TopicPartitionOffset(topicPartition.Topic, topicPartition.Partition, 0));
|
||||||
}
|
}
|
||||||
Console.WriteLine("assignment seek to beginning successfully");
|
Console.WriteLine("Assignment seek to beginning successfully");
|
||||||
// poll data again
|
|
||||||
for (int i = 0; i < 50; i++)
|
|
||||||
{
|
|
||||||
// consume message with using block to ensure the result is disposed
|
|
||||||
using (var cr = consumer.Consume(100))
|
|
||||||
{
|
|
||||||
if (cr == null) continue;
|
|
||||||
foreach (var message in cr.Message)
|
|
||||||
{
|
|
||||||
// handle message
|
|
||||||
Console.WriteLine(
|
|
||||||
$"second data polled: {{{((DateTime)message.Value["ts"]).ToString("yyyy-MM-dd HH:mm:ss.fff")}, " +
|
|
||||||
$"{message.Value["current"]}, {message.Value["voltage"]}, {message.Value["phase"]}}}");
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
catch (TDengineError e)
|
catch (TDengineError e)
|
||||||
{
|
{
|
||||||
// handle TDengine error
|
// handle TDengine error
|
||||||
Console.WriteLine("Failed to seek; ErrCode:" + e.Code + "; ErrMessage: " + e.Error);
|
Console.WriteLine("Seek example failed; ErrCode:" + e.Code + "; ErrMessage: " + e.Error);
|
||||||
throw;
|
throw;
|
||||||
}
|
}
|
||||||
catch (Exception e)
|
catch (Exception e)
|
||||||
{
|
{
|
||||||
// handle other exceptions
|
// handle other exceptions
|
||||||
Console.WriteLine("Failed to seek; Err:" + e.Message);
|
Console.WriteLine("Seek example failed; ErrMessage: " + e.Message);
|
||||||
throw;
|
throw;
|
||||||
}
|
}
|
||||||
// ANCHOR_END: seek
|
// ANCHOR_END: seek
|
||||||
|
@ -200,18 +191,19 @@ namespace TMQExample
|
||||||
{
|
{
|
||||||
cr.TopicPartitionOffset,
|
cr.TopicPartitionOffset,
|
||||||
});
|
});
|
||||||
|
Console.WriteLine("Commit offset manually successfully.");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
catch (TDengineError e)
|
catch (TDengineError e)
|
||||||
{
|
{
|
||||||
// handle TDengine error
|
// handle TDengine error
|
||||||
Console.WriteLine("Failed to commit offset; ErrCode:" + e.Code + "; ErrMessage: " + e.Error);
|
Console.WriteLine("Failed to execute consumer functions. ErrCode:" + e.Code + "; ErrMessage: " + e.Error);
|
||||||
throw;
|
throw;
|
||||||
}
|
}
|
||||||
catch (Exception e)
|
catch (Exception e)
|
||||||
{
|
{
|
||||||
// handle other exceptions
|
// handle other exceptions
|
||||||
Console.WriteLine("Failed to commit offset; Err:" + e.Message);
|
Console.WriteLine("Failed to execute consumer functions. ErrMessage:" + e.Message);
|
||||||
throw;
|
throw;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -229,19 +221,20 @@ namespace TMQExample
|
||||||
catch (TDengineError e)
|
catch (TDengineError e)
|
||||||
{
|
{
|
||||||
// handle TDengine error
|
// handle TDengine error
|
||||||
Console.WriteLine("Failed to unsubscribe consumer; ErrCode:" + e.Code + "; ErrMessage: " + e.Error);
|
Console.WriteLine("Failed to unsubscribe consumer. ErrCode:" + e.Code + "; ErrMessage: " + e.Error);
|
||||||
throw;
|
throw;
|
||||||
}
|
}
|
||||||
catch (Exception e)
|
catch (Exception e)
|
||||||
{
|
{
|
||||||
// handle other exceptions
|
// handle other exceptions
|
||||||
Console.WriteLine("Failed to unsubscribe consumer; Err:" + e.Message);
|
Console.WriteLine("Failed to unsubscribe consumer. Err: " + e.Message);
|
||||||
throw;
|
throw;
|
||||||
}
|
}
|
||||||
finally
|
finally
|
||||||
{
|
{
|
||||||
// close consumer
|
// close consumer
|
||||||
consumer.Close();
|
consumer.Close();
|
||||||
|
Console.WriteLine("Consumer closed successfully.");
|
||||||
}
|
}
|
||||||
// ANCHOR_END: close
|
// ANCHOR_END: close
|
||||||
}
|
}
|
||||||
|
|
|
@ -11,13 +11,15 @@ namespace Examples
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
var builder = new ConnectionStringBuilder("protocol=WebSocket;host=127.0.0.1;port=6041;useSSL=false;username=root;password=taosdata");
|
var connectionString =
|
||||||
|
"protocol=WebSocket;host=127.0.0.1;port=6041;useSSL=false;username=root;password=taosdata";
|
||||||
|
var builder = new ConnectionStringBuilder(connectionString);
|
||||||
using (var client = DbDriver.Open(builder))
|
using (var client = DbDriver.Open(builder))
|
||||||
{
|
{
|
||||||
CreateDatabaseAndTable(client);
|
CreateDatabaseAndTable(client,connectionString);
|
||||||
InsertData(client);
|
InsertData(client,connectionString);
|
||||||
QueryData(client);
|
QueryData(client,connectionString);
|
||||||
QueryWithReqId(client);
|
QueryWithReqId(client,connectionString);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
catch (TDengineError e)
|
catch (TDengineError e)
|
||||||
|
@ -34,40 +36,40 @@ namespace Examples
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private static void CreateDatabaseAndTable(ITDengineClient client)
|
private static void CreateDatabaseAndTable(ITDengineClient client, string connectionString)
|
||||||
{
|
{
|
||||||
// ANCHOR: create_db_and_table
|
// ANCHOR: create_db_and_table
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
// create database
|
// create database
|
||||||
var affected = client.Exec("CREATE DATABASE IF NOT EXISTS power");
|
var affected = client.Exec("CREATE DATABASE IF NOT EXISTS power");
|
||||||
Console.WriteLine($"Create database power, affected rows: {affected}");
|
Console.WriteLine($"Create database power successfully, rowsAffected: {affected}");
|
||||||
// create table
|
// create table
|
||||||
affected = client.Exec(
|
affected = client.Exec(
|
||||||
"CREATE STABLE IF NOT EXISTS power.meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (groupId INT, location BINARY(24))");
|
"CREATE STABLE IF NOT EXISTS power.meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (groupId INT, location BINARY(24))");
|
||||||
Console.WriteLine($"Create table meters, affected rows: {affected}");
|
Console.WriteLine($"Create stable power.meters successfully, rowsAffected: {affected}");
|
||||||
}
|
}
|
||||||
catch (TDengineError e)
|
catch (TDengineError e)
|
||||||
{
|
{
|
||||||
// handle TDengine error
|
// handle TDengine error
|
||||||
Console.WriteLine("Failed to create db and table; ErrCode:" + e.Code + "; ErrMessage: " + e.Error);
|
Console.WriteLine("Failed to create db and table,url:" + connectionString +"; ErrCode:" + e.Code + "; ErrMessage: " + e.Error);
|
||||||
throw;
|
throw;
|
||||||
}
|
}
|
||||||
catch (Exception e)
|
catch (Exception e)
|
||||||
{
|
{
|
||||||
// handle other exceptions
|
// handle other exceptions
|
||||||
Console.WriteLine("Failed to create db and table; Err:" + e.Message);
|
Console.WriteLine("Failed to create db and table, url:" + connectionString + "; ErrMessage: " + e.Message);
|
||||||
throw;
|
throw;
|
||||||
}
|
}
|
||||||
// ANCHOR_END: create_db_and_table
|
// ANCHOR_END: create_db_and_table
|
||||||
}
|
}
|
||||||
|
|
||||||
private static void InsertData(ITDengineClient client)
|
private static void InsertData(ITDengineClient client,string connectionString)
|
||||||
{
|
{
|
||||||
// ANCHOR: insert_data
|
// ANCHOR: insert_data
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
// insert data
|
// insert data, please make sure the database and table are created before
|
||||||
var insertQuery = "INSERT INTO " +
|
var insertQuery = "INSERT INTO " +
|
||||||
"power.d1001 USING power.meters TAGS(2,'California.SanFrancisco') " +
|
"power.d1001 USING power.meters TAGS(2,'California.SanFrancisco') " +
|
||||||
"VALUES " +
|
"VALUES " +
|
||||||
|
@ -78,29 +80,29 @@ namespace Examples
|
||||||
"VALUES " +
|
"VALUES " +
|
||||||
"(NOW + 1a, 10.30000, 218, 0.25000) ";
|
"(NOW + 1a, 10.30000, 218, 0.25000) ";
|
||||||
var affectedRows = client.Exec(insertQuery);
|
var affectedRows = client.Exec(insertQuery);
|
||||||
Console.WriteLine("insert " + affectedRows + " rows to power.meters successfully.");
|
Console.WriteLine("Successfully inserted " + affectedRows + " rows to power.meters.");
|
||||||
}
|
}
|
||||||
catch (TDengineError e)
|
catch (TDengineError e)
|
||||||
{
|
{
|
||||||
// handle TDengine error
|
// handle TDengine error
|
||||||
Console.WriteLine("Failed to insert data to power.meters; ErrCode:" + e.Code + "; ErrMessage: " + e.Error);
|
Console.WriteLine("Failed to insert data to power.meters, url:" + connectionString + "; ErrCode:" + e.Code + "; ErrMessage: " + e.Error);
|
||||||
throw;
|
throw;
|
||||||
}
|
}
|
||||||
catch (Exception e)
|
catch (Exception e)
|
||||||
{
|
{
|
||||||
// handle other exceptions
|
// handle other exceptions
|
||||||
Console.WriteLine("Failed to insert data to power.meters; Err:" + e.Message);
|
Console.WriteLine("Failed to insert data to power.meters, url:" + connectionString + "; ErrMessage: " + e.Message);
|
||||||
throw;
|
throw;
|
||||||
}
|
}
|
||||||
// ANCHOR_END: insert_data
|
// ANCHOR_END: insert_data
|
||||||
}
|
}
|
||||||
|
|
||||||
private static void QueryData(ITDengineClient client)
|
private static void QueryData(ITDengineClient client,string connectionString)
|
||||||
{
|
{
|
||||||
// ANCHOR: select_data
|
// ANCHOR: select_data
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
// query data
|
// query data, make sure the database and table are created before
|
||||||
var query = "SELECT ts, current, location FROM power.meters limit 100";
|
var query = "SELECT ts, current, location FROM power.meters limit 100";
|
||||||
using (var rows = client.Query(query))
|
using (var rows = client.Query(query))
|
||||||
{
|
{
|
||||||
|
@ -117,27 +119,28 @@ namespace Examples
|
||||||
catch (TDengineError e)
|
catch (TDengineError e)
|
||||||
{
|
{
|
||||||
// handle TDengine error
|
// handle TDengine error
|
||||||
Console.WriteLine("Failed to query data from power.meters; ErrCode:" + e.Code + "; ErrMessage: " + e.Error);
|
Console.WriteLine("Failed to query data from power.meters, url:" + connectionString + "; ErrCode:" + e.Code + "; ErrMessage: " + e.Error);
|
||||||
throw;
|
throw;
|
||||||
}
|
}
|
||||||
catch (Exception e)
|
catch (Exception e)
|
||||||
{
|
{
|
||||||
// handle other exceptions
|
// handle other exceptions
|
||||||
Console.WriteLine("Failed to query data from power.meters; Err:" + e.Message);
|
Console.WriteLine("Failed to query data from power.meters, url:" + connectionString + "; ErrMessage: " + e.Message);
|
||||||
throw;
|
throw;
|
||||||
}
|
}
|
||||||
// ANCHOR_END: select_data
|
// ANCHOR_END: select_data
|
||||||
}
|
}
|
||||||
|
|
||||||
private static void QueryWithReqId(ITDengineClient client)
|
private static void QueryWithReqId(ITDengineClient client,string connectionString)
|
||||||
{
|
{
|
||||||
// ANCHOR: query_id
|
// ANCHOR: query_id
|
||||||
|
var reqId = (long)3;
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
// query data
|
// query data
|
||||||
var query = "SELECT ts, current, location FROM power.meters limit 1";
|
var query = "SELECT ts, current, location FROM power.meters limit 1";
|
||||||
// query with request id 3
|
// query with request id 3
|
||||||
using (var rows = client.Query(query,3))
|
using (var rows = client.Query(query,reqId))
|
||||||
{
|
{
|
||||||
while (rows.Read())
|
while (rows.Read())
|
||||||
{
|
{
|
||||||
|
@ -152,13 +155,13 @@ namespace Examples
|
||||||
catch (TDengineError e)
|
catch (TDengineError e)
|
||||||
{
|
{
|
||||||
// handle TDengine error
|
// handle TDengine error
|
||||||
Console.WriteLine("Failed to execute sql with reqId; ErrCode:" + e.Code + "; ErrMessage: " + e.Error);
|
Console.WriteLine("Failed to execute sql with reqId: " + reqId + ", url:" + connectionString + "; ErrCode:" + e.Code + "; ErrMessage: " + e.Error);
|
||||||
throw;
|
throw;
|
||||||
}
|
}
|
||||||
catch (Exception e)
|
catch (Exception e)
|
||||||
{
|
{
|
||||||
// handle other exceptions
|
// handle other exceptions
|
||||||
Console.WriteLine("Failed to execute sql with reqId; Err:" + e.Message);
|
Console.WriteLine("Failed to execute sql with reqId: " + reqId + ", url:" + connectionString + "; ErrMessage: " + e.Message);
|
||||||
throw;
|
throw;
|
||||||
}
|
}
|
||||||
// ANCHOR_END: query_id
|
// ANCHOR_END: query_id
|
||||||
|
|
|
@ -13,9 +13,10 @@ namespace Examples
|
||||||
var numOfSubTable = 10;
|
var numOfSubTable = 10;
|
||||||
var numOfRow = 10;
|
var numOfRow = 10;
|
||||||
var random = new Random();
|
var random = new Random();
|
||||||
|
var connectionString = $"protocol=WebSocket;host={host};port=6041;useSSL=false;username=root;password=taosdata";
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
var builder = new ConnectionStringBuilder($"protocol=WebSocket;host={host};port=6041;useSSL=false;username=root;password=taosdata");
|
var builder = new ConnectionStringBuilder(connectionString);
|
||||||
using (var client = DbDriver.Open(builder))
|
using (var client = DbDriver.Open(builder))
|
||||||
{
|
{
|
||||||
// create database
|
// create database
|
||||||
|
@ -54,7 +55,7 @@ namespace Examples
|
||||||
stmt.Exec();
|
stmt.Exec();
|
||||||
// get affected rows
|
// get affected rows
|
||||||
var affectedRows = stmt.Affected();
|
var affectedRows = stmt.Affected();
|
||||||
Console.WriteLine($"table {tableName} insert {affectedRows} rows.");
|
Console.WriteLine($"Successfully inserted {affectedRows} rows to {tableName}.");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -62,13 +63,13 @@ namespace Examples
|
||||||
catch (TDengineError e)
|
catch (TDengineError e)
|
||||||
{
|
{
|
||||||
// handle TDengine error
|
// handle TDengine error
|
||||||
Console.WriteLine("Failed to insert to table meters using stmt; ErrCode:" + e.Code + "; ErrMessage: " + e.Error);
|
Console.WriteLine("Failed to insert to table meters using stmt, url: " + connectionString + "; ErrCode:" + e.Code + "; ErrMessage: " + e.Error);
|
||||||
throw;
|
throw;
|
||||||
}
|
}
|
||||||
catch (Exception e)
|
catch (Exception e)
|
||||||
{
|
{
|
||||||
// handle other exceptions
|
// handle other exceptions
|
||||||
Console.WriteLine("Failed to insert to table meters using stmt; Err:" + e.Message);
|
Console.WriteLine("Failed to insert to table meters using stmt, url: " + connectionString + "; ErrMessage: " + e.Message);
|
||||||
throw;
|
throw;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -29,26 +29,29 @@ namespace TDengineExample
|
||||||
// use database
|
// use database
|
||||||
client.Exec("USE power");
|
client.Exec("USE power");
|
||||||
// insert influx line protocol data
|
// insert influx line protocol data
|
||||||
client.SchemalessInsert(new[]{lineDemo}, TDengineSchemalessProtocol.TSDB_SML_LINE_PROTOCOL,
|
client.SchemalessInsert(new[] { lineDemo }, TDengineSchemalessProtocol.TSDB_SML_LINE_PROTOCOL,
|
||||||
TDengineSchemalessPrecision.TSDB_SML_TIMESTAMP_MILLI_SECONDS, 0, ReqId.GetReqId());
|
TDengineSchemalessPrecision.TSDB_SML_TIMESTAMP_MILLI_SECONDS, 0, ReqId.GetReqId());
|
||||||
// insert opentsdb telnet protocol data
|
// insert opentsdb telnet protocol data
|
||||||
client.SchemalessInsert(new[]{telnetDemo}, TDengineSchemalessProtocol.TSDB_SML_TELNET_PROTOCOL,
|
client.SchemalessInsert(new[] { telnetDemo }, TDengineSchemalessProtocol.TSDB_SML_TELNET_PROTOCOL,
|
||||||
TDengineSchemalessPrecision.TSDB_SML_TIMESTAMP_MILLI_SECONDS, 0, ReqId.GetReqId());
|
TDengineSchemalessPrecision.TSDB_SML_TIMESTAMP_MILLI_SECONDS, 0, ReqId.GetReqId());
|
||||||
// insert json data
|
// insert json data
|
||||||
client.SchemalessInsert(new []{jsonDemo}, TDengineSchemalessProtocol.TSDB_SML_JSON_PROTOCOL,
|
client.SchemalessInsert(new[] { jsonDemo }, TDengineSchemalessProtocol.TSDB_SML_JSON_PROTOCOL,
|
||||||
TDengineSchemalessPrecision.TSDB_SML_TIMESTAMP_NOT_CONFIGURED, 0, ReqId.GetReqId());
|
TDengineSchemalessPrecision.TSDB_SML_TIMESTAMP_NOT_CONFIGURED, 0, ReqId.GetReqId());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Console.WriteLine("Inserted data with schemaless successfully.");
|
||||||
}
|
}
|
||||||
catch (TDengineError e)
|
catch (TDengineError e)
|
||||||
{
|
{
|
||||||
// handle TDengine error
|
// handle TDengine error
|
||||||
Console.WriteLine("Failed to insert data with schemaless; ErrCode:" + e.Code + "; ErrMessage: " + e.Error);
|
Console.WriteLine("Failed to insert data with schemaless, host:" + host + "; ErrCode:" + e.Code +
|
||||||
|
"; ErrMessage: " + e.Error);
|
||||||
throw;
|
throw;
|
||||||
}
|
}
|
||||||
catch (Exception e)
|
catch (Exception e)
|
||||||
{
|
{
|
||||||
// handle other exceptions
|
// handle other exceptions
|
||||||
Console.WriteLine("Failed to insert data with schemaless; Err:" + e.Message);
|
Console.WriteLine("Failed to insert data with schemaless, host:" + host + "; ErrMessage: " + e.Message);
|
||||||
throw;
|
throw;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -10,7 +10,9 @@ namespace TMQExample
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
var builder = new ConnectionStringBuilder("protocol=WebSocket;host=127.0.0.1;port=6041;username=root;password=taosdata");
|
var builder =
|
||||||
|
new ConnectionStringBuilder(
|
||||||
|
"protocol=WebSocket;host=127.0.0.1;port=6041;username=root;password=taosdata");
|
||||||
using (var client = DbDriver.Open(builder))
|
using (var client = DbDriver.Open(builder))
|
||||||
{
|
{
|
||||||
client.Exec("CREATE DATABASE IF NOT EXISTS power");
|
client.Exec("CREATE DATABASE IF NOT EXISTS power");
|
||||||
|
@ -48,7 +50,9 @@ namespace TMQExample
|
||||||
|
|
||||||
static void InsertData()
|
static void InsertData()
|
||||||
{
|
{
|
||||||
var builder = new ConnectionStringBuilder("protocol=WebSocket;host=127.0.0.1;port=6041;username=root;password=taosdata");
|
var builder =
|
||||||
|
new ConnectionStringBuilder(
|
||||||
|
"protocol=WebSocket;host=127.0.0.1;port=6041;username=root;password=taosdata");
|
||||||
using (var client = DbDriver.Open(builder))
|
using (var client = DbDriver.Open(builder))
|
||||||
{
|
{
|
||||||
while (true)
|
while (true)
|
||||||
|
@ -64,17 +68,20 @@ namespace TMQExample
|
||||||
{
|
{
|
||||||
// ANCHOR: create_consumer
|
// ANCHOR: create_consumer
|
||||||
// consumer config
|
// consumer config
|
||||||
|
var host = "127.0.0.1";
|
||||||
|
var groupId = "group1";
|
||||||
|
var clientId = "client1";
|
||||||
var cfg = new Dictionary<string, string>()
|
var cfg = new Dictionary<string, string>()
|
||||||
{
|
{
|
||||||
{"td.connect.type", "WebSocket"},
|
{ "td.connect.type", "WebSocket" },
|
||||||
{ "td.connect.port", "6041" },
|
{ "td.connect.port", "6041" },
|
||||||
{ "auto.offset.reset", "latest" },
|
{ "auto.offset.reset", "latest" },
|
||||||
{ "msg.with.table.name", "true" },
|
{ "msg.with.table.name", "true" },
|
||||||
{ "enable.auto.commit", "true" },
|
{ "enable.auto.commit", "true" },
|
||||||
{ "auto.commit.interval.ms", "1000" },
|
{ "auto.commit.interval.ms", "1000" },
|
||||||
{ "group.id", "group1" },
|
{ "group.id", groupId },
|
||||||
{ "client.id", "client1" },
|
{ "client.id", clientId },
|
||||||
{ "td.connect.ip", "127.0.0.1" },
|
{ "td.connect.ip", host },
|
||||||
{ "td.connect.user", "root" },
|
{ "td.connect.user", "root" },
|
||||||
{ "td.connect.pass", "taosdata" },
|
{ "td.connect.pass", "taosdata" },
|
||||||
};
|
};
|
||||||
|
@ -83,17 +90,20 @@ namespace TMQExample
|
||||||
{
|
{
|
||||||
// create consumer
|
// create consumer
|
||||||
consumer = new ConsumerBuilder<Dictionary<string, object>>(cfg).Build();
|
consumer = new ConsumerBuilder<Dictionary<string, object>>(cfg).Build();
|
||||||
|
Console.WriteLine("Create consumer successfully, host: " + host + ", groupId: " + groupId +
|
||||||
|
", clientId: " + clientId);
|
||||||
}
|
}
|
||||||
catch (TDengineError e)
|
catch (TDengineError e)
|
||||||
{
|
{
|
||||||
// handle TDengine error
|
// handle TDengine error
|
||||||
Console.WriteLine("Failed to create consumer; ErrCode:" + e.Code + "; ErrMessage: " + e.Error);
|
Console.WriteLine("Failed to create websocket consumer, host : " + host + "; ErrCode:" + e.Code +
|
||||||
|
"; ErrMessage: " + e.Error);
|
||||||
throw;
|
throw;
|
||||||
}
|
}
|
||||||
catch (Exception e)
|
catch (Exception e)
|
||||||
{
|
{
|
||||||
// handle other exceptions
|
// handle other exceptions
|
||||||
Console.WriteLine("Failed to create consumer; Err:" + e.Message);
|
Console.WriteLine("Failed to create websocket consumer, host : " + host + "; ErrMessage: " + e.Message);
|
||||||
throw;
|
throw;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -108,6 +118,7 @@ namespace TMQExample
|
||||||
{
|
{
|
||||||
// subscribe
|
// subscribe
|
||||||
consumer.Subscribe(new List<string>() { "topic_meters" });
|
consumer.Subscribe(new List<string>() { "topic_meters" });
|
||||||
|
Console.WriteLine("Subscribe topics successfully");
|
||||||
for (int i = 0; i < 50; i++)
|
for (int i = 0; i < 50; i++)
|
||||||
{
|
{
|
||||||
// consume message with using block to ensure the result is disposed
|
// consume message with using block to ensure the result is disposed
|
||||||
|
@ -118,7 +129,7 @@ namespace TMQExample
|
||||||
{
|
{
|
||||||
// handle message
|
// handle message
|
||||||
Console.WriteLine(
|
Console.WriteLine(
|
||||||
$"data {{{((DateTime)message.Value["ts"]).ToString("yyyy-MM-dd HH:mm:ss.fff")}, " +
|
$"data: {{{((DateTime)message.Value["ts"]).ToString("yyyy-MM-dd HH:mm:ss.fff")}, " +
|
||||||
$"{message.Value["current"]}, {message.Value["voltage"]}, {message.Value["phase"]}}}");
|
$"{message.Value["current"]}, {message.Value["voltage"]}, {message.Value["phase"]}}}");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -133,7 +144,7 @@ namespace TMQExample
|
||||||
catch (Exception e)
|
catch (Exception e)
|
||||||
{
|
{
|
||||||
// handle other exceptions
|
// handle other exceptions
|
||||||
Console.WriteLine("Failed to poll data; Err:" + e.Message);
|
Console.WriteLine("Failed to poll data; ErrMessage:" + e.Message);
|
||||||
throw;
|
throw;
|
||||||
}
|
}
|
||||||
// ANCHOR_END: subscribe
|
// ANCHOR_END: subscribe
|
||||||
|
@ -146,40 +157,24 @@ namespace TMQExample
|
||||||
{
|
{
|
||||||
// get assignment
|
// get assignment
|
||||||
var assignment = consumer.Assignment;
|
var assignment = consumer.Assignment;
|
||||||
|
Console.WriteLine($"Now assignment: {assignment}");
|
||||||
// seek to the beginning
|
// seek to the beginning
|
||||||
foreach (var topicPartition in assignment)
|
foreach (var topicPartition in assignment)
|
||||||
{
|
{
|
||||||
consumer.Seek(new TopicPartitionOffset(topicPartition.Topic, topicPartition.Partition, 0));
|
consumer.Seek(new TopicPartitionOffset(topicPartition.Topic, topicPartition.Partition, 0));
|
||||||
}
|
}
|
||||||
Console.WriteLine("assignment seek to beginning successfully");
|
Console.WriteLine("Assignment seek to beginning successfully");
|
||||||
// poll data again
|
|
||||||
for (int i = 0; i < 50; i++)
|
|
||||||
{
|
|
||||||
// consume message with using block to ensure the result is disposed
|
|
||||||
using (var cr = consumer.Consume(100))
|
|
||||||
{
|
|
||||||
if (cr == null) continue;
|
|
||||||
foreach (var message in cr.Message)
|
|
||||||
{
|
|
||||||
// handle message
|
|
||||||
Console.WriteLine(
|
|
||||||
$"second data polled: {{{((DateTime)message.Value["ts"]).ToString("yyyy-MM-dd HH:mm:ss.fff")}, " +
|
|
||||||
$"{message.Value["current"]}, {message.Value["voltage"]}, {message.Value["phase"]}}}");
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
catch (TDengineError e)
|
catch (TDengineError e)
|
||||||
{
|
{
|
||||||
// handle TDengine error
|
// handle TDengine error
|
||||||
Console.WriteLine("Failed to seek; ErrCode:" + e.Code + "; ErrMessage: " + e.Error);
|
Console.WriteLine("Seek example failed; ErrCode:" + e.Code + "; ErrMessage: " + e.Error);
|
||||||
throw;
|
throw;
|
||||||
}
|
}
|
||||||
catch (Exception e)
|
catch (Exception e)
|
||||||
{
|
{
|
||||||
// handle other exceptions
|
// handle other exceptions
|
||||||
Console.WriteLine("Failed to seek; Err:" + e.Message);
|
Console.WriteLine("Seek example failed; ErrMessage: " + e.Message);
|
||||||
throw;
|
throw;
|
||||||
}
|
}
|
||||||
// ANCHOR_END: seek
|
// ANCHOR_END: seek
|
||||||
|
@ -201,18 +196,19 @@ namespace TMQExample
|
||||||
{
|
{
|
||||||
cr.TopicPartitionOffset,
|
cr.TopicPartitionOffset,
|
||||||
});
|
});
|
||||||
|
Console.WriteLine("Commit offset manually successfully.");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
catch (TDengineError e)
|
catch (TDengineError e)
|
||||||
{
|
{
|
||||||
// handle TDengine error
|
// handle TDengine error
|
||||||
Console.WriteLine("Failed to commit offset; ErrCode:" + e.Code + "; ErrMessage: " + e.Error);
|
Console.WriteLine("Failed to execute consumer functions. ErrCode:" + e.Code + "; ErrMessage: " + e.Error);
|
||||||
throw;
|
throw;
|
||||||
}
|
}
|
||||||
catch (Exception e)
|
catch (Exception e)
|
||||||
{
|
{
|
||||||
// handle other exceptions
|
// handle other exceptions
|
||||||
Console.WriteLine("Failed to commit offset; Err:" + e.Message);
|
Console.WriteLine("Failed to execute consumer functions. ErrMessage:" + e.Message);
|
||||||
throw;
|
throw;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -230,19 +226,20 @@ namespace TMQExample
|
||||||
catch (TDengineError e)
|
catch (TDengineError e)
|
||||||
{
|
{
|
||||||
// handle TDengine error
|
// handle TDengine error
|
||||||
Console.WriteLine("Failed to unsubscribe consumer; ErrCode:" + e.Code + "; ErrMessage: " + e.Error);
|
Console.WriteLine("Failed to unsubscribe consumer. ErrCode:" + e.Code + "; ErrMessage: " + e.Error);
|
||||||
throw;
|
throw;
|
||||||
}
|
}
|
||||||
catch (Exception e)
|
catch (Exception e)
|
||||||
{
|
{
|
||||||
// handle other exceptions
|
// handle other exceptions
|
||||||
Console.WriteLine("Failed to unsubscribe consumer; Err:" + e.Message);
|
Console.WriteLine("Failed to unsubscribe consumer. Err: " + e.Message);
|
||||||
throw;
|
throw;
|
||||||
}
|
}
|
||||||
finally
|
finally
|
||||||
{
|
{
|
||||||
// close consumer
|
// close consumer
|
||||||
consumer.Close();
|
consumer.Close();
|
||||||
|
Console.WriteLine("Consumer closed successfully.");
|
||||||
}
|
}
|
||||||
// ANCHOR_END: close
|
// ANCHOR_END: close
|
||||||
}
|
}
|
||||||
|
|
|
@ -15,7 +15,7 @@ func main() {
|
||||||
var taosDSN = "root:taosdata@tcp(localhost:6030)/"
|
var taosDSN = "root:taosdata@tcp(localhost:6030)/"
|
||||||
taos, err := sql.Open("taosSql", taosDSN)
|
taos, err := sql.Open("taosSql", taosDSN)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatalln("failed to connect TDengine, err:", err)
|
log.Fatalln("Failed to connect to " + taosDSN + "; ErrMessage: " + err.Error())
|
||||||
}
|
}
|
||||||
fmt.Println("Connected to " + taosDSN + " successfully.")
|
fmt.Println("Connected to " + taosDSN + " successfully.")
|
||||||
defer taos.Close()
|
defer taos.Close()
|
||||||
|
|
|
@ -15,7 +15,7 @@ func main() {
|
||||||
var taosDSN = "root:taosdata@http(localhost:6041)/"
|
var taosDSN = "root:taosdata@http(localhost:6041)/"
|
||||||
taos, err := sql.Open("taosRestful", taosDSN)
|
taos, err := sql.Open("taosRestful", taosDSN)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatalln("failed to connect TDengine, err:", err)
|
log.Fatalln("Failed to connect to " + taosDSN + "; ErrMessage: " + err.Error())
|
||||||
}
|
}
|
||||||
fmt.Println("Connected to " + taosDSN + " successfully.")
|
fmt.Println("Connected to " + taosDSN + " successfully.")
|
||||||
defer taos.Close()
|
defer taos.Close()
|
||||||
|
|
|
@ -15,7 +15,7 @@ func main() {
|
||||||
var taosDSN = "root:taosdata@ws(localhost:6041)/"
|
var taosDSN = "root:taosdata@ws(localhost:6041)/"
|
||||||
taos, err := sql.Open("taosWS", taosDSN)
|
taos, err := sql.Open("taosWS", taosDSN)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatalln("failed to connect TDengine, err:", err)
|
log.Fatalln("Failed to connect to " + taosDSN + "; ErrMessage: " + err.Error())
|
||||||
}
|
}
|
||||||
fmt.Println("Connected to " + taosDSN + " successfully.")
|
fmt.Println("Connected to " + taosDSN + " successfully.")
|
||||||
defer taos.Close()
|
defer taos.Close()
|
||||||
|
|
|
@ -11,19 +11,21 @@ import (
|
||||||
)
|
)
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
db, err := sql.Open("taosSql", "root:taosdata@tcp(localhost:6030)/")
|
taosDSN := "root:taosdata@tcp(localhost:6030)/"
|
||||||
|
db, err := sql.Open("taosSql", taosDSN)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal("Open database error: ", err)
|
log.Fatalln("Failed to connect to " + taosDSN + "; ErrMessage: " + err.Error())
|
||||||
}
|
}
|
||||||
defer db.Close()
|
defer db.Close()
|
||||||
initEnv(db)
|
initEnv(db)
|
||||||
// ANCHOR: query_id
|
// ANCHOR: query_id
|
||||||
// use context to set request id
|
// use context to set request id
|
||||||
ctx := context.WithValue(context.Background(), "taos_req_id", int64(3))
|
reqId := int64(3)
|
||||||
|
ctx := context.WithValue(context.Background(), "taos_req_id", reqId)
|
||||||
// execute query with context
|
// execute query with context
|
||||||
rows, err := db.QueryContext(ctx, "SELECT ts, current, location FROM power.meters limit 1")
|
rows, err := db.QueryContext(ctx, "SELECT ts, current, location FROM power.meters limit 1")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal("Query error: ", err)
|
log.Fatalf("Failed to execute sql with reqId: %d, url: %s; ErrMessage: %s\n", reqId, taosDSN, err.Error())
|
||||||
}
|
}
|
||||||
for rows.Next() {
|
for rows.Next() {
|
||||||
var (
|
var (
|
||||||
|
|
|
@ -1,6 +1,7 @@
|
||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"fmt"
|
||||||
"log"
|
"log"
|
||||||
|
|
||||||
"github.com/taosdata/driver-go/v3/af"
|
"github.com/taosdata/driver-go/v3/af"
|
||||||
|
@ -14,30 +15,31 @@ func main() {
|
||||||
|
|
||||||
conn, err := af.Open(host, "root", "taosdata", "", 0)
|
conn, err := af.Open(host, "root", "taosdata", "", 0)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal("failed to connect TDengine, err:", err)
|
log.Fatalln("Failed to connect to host: " + host + "; ErrMessage: " + err.Error())
|
||||||
}
|
}
|
||||||
defer conn.Close()
|
defer conn.Close()
|
||||||
_, err = conn.Exec("CREATE DATABASE IF NOT EXISTS power")
|
_, err = conn.Exec("CREATE DATABASE IF NOT EXISTS power")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal("failed to create database, err:", err)
|
log.Fatalln("Failed to create db host: " + host + "; ErrMessage: " + err.Error())
|
||||||
}
|
}
|
||||||
_, err = conn.Exec("USE power")
|
_, err = conn.Exec("USE power")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal("failed to use database, err:", err)
|
log.Fatalln("Failed to use db host: " + host + "; ErrMessage: " + err.Error())
|
||||||
}
|
}
|
||||||
// insert influxdb line protocol
|
// insert influxdb line protocol
|
||||||
err = conn.InfluxDBInsertLines([]string{lineDemo}, "ms")
|
err = conn.InfluxDBInsertLines([]string{lineDemo}, "ms")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal("failed to insert influxdb line protocol, err:", err)
|
log.Fatalln("Failed to insert data with schemaless, host: " + host + "; ErrMessage: " + err.Error())
|
||||||
}
|
}
|
||||||
// insert opentsdb telnet protocol
|
// insert opentsdb telnet protocol
|
||||||
err = conn.OpenTSDBInsertTelnetLines([]string{telnetDemo})
|
err = conn.OpenTSDBInsertTelnetLines([]string{telnetDemo})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal("failed to insert opentsdb telnet line protocol, err:", err)
|
log.Fatalln("Failed to insert data with schemaless, host: " + host + "; ErrMessage: " + err.Error())
|
||||||
}
|
}
|
||||||
// insert opentsdb json protocol
|
// insert opentsdb json protocol
|
||||||
err = conn.OpenTSDBInsertJsonPayload(jsonDemo)
|
err = conn.OpenTSDBInsertJsonPayload(jsonDemo)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal("failed to insert opentsdb json format protocol, err:", err)
|
log.Fatalln("Failed to insert data with schemaless, host: " + host + "; ErrMessage: " + err.Error())
|
||||||
}
|
}
|
||||||
|
fmt.Println("Inserted data with schemaless successfully.")
|
||||||
}
|
}
|
||||||
|
|
|
@ -17,14 +17,15 @@ func main() {
|
||||||
telnetDemo := "metric_telnet 1707095283260 4 host=host0 interface=eth0"
|
telnetDemo := "metric_telnet 1707095283260 4 host=host0 interface=eth0"
|
||||||
jsonDemo := "{\"metric\": \"metric_json\",\"timestamp\": 1626846400,\"value\": 10.3, \"tags\": {\"groupid\": 2, \"location\": \"California.SanFrancisco\", \"id\": \"d1001\"}}"
|
jsonDemo := "{\"metric\": \"metric_json\",\"timestamp\": 1626846400,\"value\": 10.3, \"tags\": {\"groupid\": 2, \"location\": \"California.SanFrancisco\", \"id\": \"d1001\"}}"
|
||||||
|
|
||||||
db, err := sql.Open("taosWS", fmt.Sprintf("root:taosdata@ws(%s:6041)/", host))
|
taosDSN := fmt.Sprintf("root:taosdata@ws(%s:6041)/", host)
|
||||||
|
db, err := sql.Open("taosWS", taosDSN)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal("failed to connect TDengine, err:", err)
|
log.Fatalln("Failed to connect to host: " + host + "; ErrMessage: " + err.Error())
|
||||||
}
|
}
|
||||||
defer db.Close()
|
defer db.Close()
|
||||||
_, err = db.Exec("CREATE DATABASE IF NOT EXISTS power")
|
_, err = db.Exec("CREATE DATABASE IF NOT EXISTS power")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal("failed to create database, err:", err)
|
log.Fatalln("Failed to create db host: " + host + "; ErrMessage: " + err.Error())
|
||||||
}
|
}
|
||||||
s, err := schemaless.NewSchemaless(schemaless.NewConfig("ws://localhost:6041", 1,
|
s, err := schemaless.NewSchemaless(schemaless.NewConfig("ws://localhost:6041", 1,
|
||||||
schemaless.SetDb("power"),
|
schemaless.SetDb("power"),
|
||||||
|
@ -34,21 +35,22 @@ func main() {
|
||||||
schemaless.SetPassword("taosdata"),
|
schemaless.SetPassword("taosdata"),
|
||||||
))
|
))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal("failed to create schemaless connection, err:", err)
|
log.Fatalln("Failed to connect to host: " + host + "; ErrMessage: " + err.Error())
|
||||||
}
|
}
|
||||||
// insert influxdb line protocol
|
// insert influxdb line protocol
|
||||||
err = s.Insert(lineDemo, schemaless.InfluxDBLineProtocol, "ms", 0, common.GetReqID())
|
err = s.Insert(lineDemo, schemaless.InfluxDBLineProtocol, "ms", 0, common.GetReqID())
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal("failed to insert influxdb line protocol, err:", err)
|
log.Fatalln("Failed to insert data with schemaless, host:" + host + "; ErrMessage: " + err.Error())
|
||||||
}
|
}
|
||||||
// insert opentsdb telnet line protocol
|
// insert opentsdb telnet line protocol
|
||||||
err = s.Insert(telnetDemo, schemaless.OpenTSDBTelnetLineProtocol, "ms", 0, common.GetReqID())
|
err = s.Insert(telnetDemo, schemaless.OpenTSDBTelnetLineProtocol, "ms", 0, common.GetReqID())
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal("failed to insert opentsdb telnet line protocol, err:", err)
|
log.Fatalln("Failed to insert data with schemaless, host: " + host + "; ErrMessage: " + err.Error())
|
||||||
}
|
}
|
||||||
// insert opentsdb json format protocol
|
// insert opentsdb json format protocol
|
||||||
err = s.Insert(jsonDemo, schemaless.OpenTSDBJsonFormatProtocol, "s", 0, common.GetReqID())
|
err = s.Insert(jsonDemo, schemaless.OpenTSDBJsonFormatProtocol, "s", 0, common.GetReqID())
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal("failed to insert opentsdb json format protocol, err:", err)
|
log.Fatalln("Failed to insert data with schemaless, host: " + host + "; ErrMessage: " + err.Error())
|
||||||
}
|
}
|
||||||
|
fmt.Println("Inserted data with schemaless successfully.")
|
||||||
}
|
}
|
||||||
|
|
|
@ -10,39 +10,35 @@ import (
|
||||||
)
|
)
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
db, err := sql.Open("taosSql", "root:taosdata@tcp(localhost:6030)/")
|
var taosDSN = "root:taosdata@tcp(localhost:6030)/"
|
||||||
|
db, err := sql.Open("taosSql", taosDSN)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal("open database failed:", err)
|
log.Fatalln("Failed to connect to " + taosDSN + "; ErrMessage: " + err.Error())
|
||||||
}
|
}
|
||||||
defer db.Close()
|
defer db.Close()
|
||||||
// ANCHOR: create_db_and_table
|
// ANCHOR: create_db_and_table
|
||||||
// create database
|
// create database
|
||||||
res, err := db.Exec("CREATE DATABASE IF NOT EXISTS power")
|
res, err := db.Exec("CREATE DATABASE IF NOT EXISTS power")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal("create database failed:", err)
|
log.Fatalln("Failed to create db, url:" + taosDSN + "; ErrMessage: " + err.Error())
|
||||||
}
|
}
|
||||||
affected, err := res.RowsAffected()
|
rowsAffected, err := res.RowsAffected()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal("get affected rows failed:", err)
|
log.Fatalln("Failed to get create db rowsAffected, url:" + taosDSN + "; ErrMessage: " + err.Error())
|
||||||
}
|
}
|
||||||
fmt.Println("create database affected:", affected)
|
// you can check rowsAffected here
|
||||||
// use database
|
fmt.Println("Create database power successfully, rowsAffected: ", rowsAffected)
|
||||||
res, err = db.Exec("USE power")
|
|
||||||
if err != nil {
|
|
||||||
log.Fatal("use database failed:", err)
|
|
||||||
}
|
|
||||||
affected, err = res.RowsAffected()
|
|
||||||
if err != nil {
|
|
||||||
log.Fatal("get affected rows failed:", err)
|
|
||||||
}
|
|
||||||
fmt.Println("use database affected:", affected)
|
|
||||||
// create table
|
// create table
|
||||||
res, err = db.Exec("CREATE STABLE IF NOT EXISTS power.meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (groupId INT, location BINARY(24))")
|
res, err = db.Exec("CREATE STABLE IF NOT EXISTS power.meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (groupId INT, location BINARY(24))")
|
||||||
affected, err = res.RowsAffected()
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal("create table failed:", err)
|
log.Fatalln("Failed to create db and table, url:" + taosDSN + "; ErrMessage: " + err.Error())
|
||||||
}
|
}
|
||||||
fmt.Println("create table affected:", affected)
|
rowsAffected, err = res.RowsAffected()
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalln("Failed to get create db rowsAffected, url:" + taosDSN + "; ErrMessage: " + err.Error())
|
||||||
|
}
|
||||||
|
// you can check rowsAffected here
|
||||||
|
fmt.Println("Create stable power.meters successfully, rowsAffected:", rowsAffected)
|
||||||
// ANCHOR_END: create_db_and_table
|
// ANCHOR_END: create_db_and_table
|
||||||
// ANCHOR: insert_data
|
// ANCHOR: insert_data
|
||||||
// insert data, please make sure the database and table are created before
|
// insert data, please make sure the database and table are created before
|
||||||
|
@ -57,20 +53,20 @@ func main() {
|
||||||
"(NOW + 1a, 10.30000, 218, 0.25000) "
|
"(NOW + 1a, 10.30000, 218, 0.25000) "
|
||||||
res, err = db.Exec(insertQuery)
|
res, err = db.Exec(insertQuery)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal("insert data failed:", err)
|
log.Fatal("Failed to insert data to power.meters, url:" + taosDSN + "; ErrMessage: " + err.Error())
|
||||||
}
|
}
|
||||||
affected, err = res.RowsAffected()
|
rowsAffected, err = res.RowsAffected()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal("get affected rows failed:", err)
|
log.Fatal("Failed to get insert rowsAffected, url:" + taosDSN + "; ErrMessage: " + err.Error())
|
||||||
}
|
}
|
||||||
// you can check affectedRows here
|
// you can check affectedRows here
|
||||||
fmt.Println("insert data affected:", affected)
|
fmt.Printf("Successfully inserted %d rows to power.meters.\n", rowsAffected)
|
||||||
// ANCHOR_END: insert_data
|
// ANCHOR_END: insert_data
|
||||||
// ANCHOR: select_data
|
// ANCHOR: select_data
|
||||||
// query data, make sure the database and table are created before
|
// query data, make sure the database and table are created before
|
||||||
rows, err := db.Query("SELECT ts, current, location FROM power.meters limit 100")
|
rows, err := db.Query("SELECT ts, current, location FROM power.meters limit 100")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal("query data failed:", err)
|
log.Fatal("Failed to query data from power.meters, url:" + taosDSN + "; ErrMessage: " + err.Error())
|
||||||
}
|
}
|
||||||
for rows.Next() {
|
for rows.Next() {
|
||||||
var (
|
var (
|
||||||
|
@ -80,7 +76,7 @@ func main() {
|
||||||
)
|
)
|
||||||
err = rows.Scan(&ts, ¤t, &location)
|
err = rows.Scan(&ts, ¤t, &location)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal("scan data failed:", err)
|
log.Fatal("Failed to scan data, url:" + taosDSN + "; ErrMessage: " + err.Error())
|
||||||
}
|
}
|
||||||
// you can check data here
|
// you can check data here
|
||||||
fmt.Printf("ts: %s, current: %f, location: %s\n", ts, current, location)
|
fmt.Printf("ts: %s, current: %f, location: %s\n", ts, current, location)
|
||||||
|
|
|
@ -17,28 +17,28 @@ func main() {
|
||||||
numOfRow := 10
|
numOfRow := 10
|
||||||
db, err := af.Open(host, "root", "taosdata", "", 0)
|
db, err := af.Open(host, "root", "taosdata", "", 0)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal("failed to connect TDengine, err:", err)
|
log.Fatalln("Failed to connect to " + host + "; ErrMessage: " + err.Error())
|
||||||
}
|
}
|
||||||
defer db.Close()
|
defer db.Close()
|
||||||
// prepare database and table
|
// prepare database and table
|
||||||
_, err = db.Exec("CREATE DATABASE IF NOT EXISTS power")
|
_, err = db.Exec("CREATE DATABASE IF NOT EXISTS power")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal("failed to create database, err:", err)
|
log.Fatalln("Failed to create db, host: " + host + "; ErrMessage: " + err.Error())
|
||||||
}
|
}
|
||||||
_, err = db.Exec("USE power")
|
_, err = db.Exec("USE power")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal("failed to use database, err:", err)
|
log.Fatalln("Failed to use db, host: " + host + "; ErrMessage: " + err.Error())
|
||||||
}
|
}
|
||||||
_, err = db.Exec("CREATE STABLE IF NOT EXISTS meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (groupId INT, location BINARY(24))")
|
_, err = db.Exec("CREATE STABLE IF NOT EXISTS meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (groupId INT, location BINARY(24))")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal("failed to create table, err:", err)
|
log.Fatalln("Failed to create table, host: " + host + "; ErrMessage: " + err.Error())
|
||||||
}
|
}
|
||||||
// prepare statement
|
// prepare statement
|
||||||
sql := "INSERT INTO ? USING meters TAGS(?,?) VALUES (?,?,?,?)"
|
sql := "INSERT INTO ? USING meters TAGS(?,?) VALUES (?,?,?,?)"
|
||||||
stmt := db.Stmt()
|
stmt := db.Stmt()
|
||||||
err = stmt.Prepare(sql)
|
err = stmt.Prepare(sql)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal("failed to prepare statement, err:", err)
|
log.Fatalln("Failed to prepare sql, host: " + host + "; ErrMessage: " + err.Error())
|
||||||
}
|
}
|
||||||
for i := 1; i <= numOfSubTable; i++ {
|
for i := 1; i <= numOfSubTable; i++ {
|
||||||
tableName := fmt.Sprintf("d_bind_%d", i)
|
tableName := fmt.Sprintf("d_bind_%d", i)
|
||||||
|
@ -46,7 +46,7 @@ func main() {
|
||||||
// set tableName and tags
|
// set tableName and tags
|
||||||
err = stmt.SetTableNameWithTags(tableName, tags)
|
err = stmt.SetTableNameWithTags(tableName, tags)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal("failed to set table name and tags, err:", err)
|
log.Fatalln("Failed to set table name and tags, host: " + host + "; ErrMessage: " + err.Error())
|
||||||
}
|
}
|
||||||
// bind column data
|
// bind column data
|
||||||
current := time.Now()
|
current := time.Now()
|
||||||
|
@ -58,23 +58,23 @@ func main() {
|
||||||
AddFloat(rand.Float32())
|
AddFloat(rand.Float32())
|
||||||
err = stmt.BindRow(row)
|
err = stmt.BindRow(row)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal("failed to bind row, err:", err)
|
log.Fatalln("Failed to bind params, host: " + host + "; ErrMessage: " + err.Error())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// add batch
|
// add batch
|
||||||
err = stmt.AddBatch()
|
err = stmt.AddBatch()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal("failed to add batch, err:", err)
|
log.Fatalln("Failed to add batch, host: " + host + "; ErrMessage: " + err.Error())
|
||||||
}
|
}
|
||||||
// execute batch
|
// execute batch
|
||||||
err = stmt.Execute()
|
err = stmt.Execute()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal("failed to execute batch, err:", err)
|
log.Fatalln("Failed to exec, host: " + host + "; ErrMessage: " + err.Error())
|
||||||
}
|
}
|
||||||
// get affected rows
|
// get affected rows
|
||||||
affected := stmt.GetAffectedRows()
|
affected := stmt.GetAffectedRows()
|
||||||
// you can check exeResult here
|
// you can check exeResult here
|
||||||
fmt.Printf("table %s insert %d rows.\n", tableName, affected)
|
fmt.Printf("Successfully inserted %d rows to %s.\n", affected, tableName)
|
||||||
}
|
}
|
||||||
err = stmt.Close()
|
err = stmt.Close()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|
|
@ -17,19 +17,21 @@ func main() {
|
||||||
host := "127.0.0.1"
|
host := "127.0.0.1"
|
||||||
numOfSubTable := 10
|
numOfSubTable := 10
|
||||||
numOfRow := 10
|
numOfRow := 10
|
||||||
db, err := sql.Open("taosRestful", fmt.Sprintf("root:taosdata@http(%s:6041)/", host))
|
|
||||||
|
taosDSN := fmt.Sprintf("root:taosdata@http(%s:6041)/", host)
|
||||||
|
db, err := sql.Open("taosRestful", taosDSN)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal("failed to connect TDengine, err:", err)
|
log.Fatalln("Failed to connect to " + taosDSN + "; ErrMessage: " + err.Error())
|
||||||
}
|
}
|
||||||
defer db.Close()
|
defer db.Close()
|
||||||
// prepare database and table
|
// prepare database and table
|
||||||
_, err = db.Exec("CREATE DATABASE IF NOT EXISTS power")
|
_, err = db.Exec("CREATE DATABASE IF NOT EXISTS power")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal("failed to create database, err:", err)
|
log.Fatalln("Failed to create db, url: " + taosDSN + "; ErrMessage: " + err.Error())
|
||||||
}
|
}
|
||||||
_, err = db.Exec("CREATE STABLE IF NOT EXISTS power.meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (groupId INT, location BINARY(24))")
|
_, err = db.Exec("CREATE STABLE IF NOT EXISTS power.meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (groupId INT, location BINARY(24))")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal("failed to create table, err:", err)
|
log.Fatalln("Failed to create table, url: " + taosDSN + "; ErrMessage: " + err.Error())
|
||||||
}
|
}
|
||||||
|
|
||||||
config := stmt.NewConfig(fmt.Sprintf("ws://%s:6041", host), 0)
|
config := stmt.NewConfig(fmt.Sprintf("ws://%s:6041", host), 0)
|
||||||
|
@ -41,17 +43,17 @@ func main() {
|
||||||
|
|
||||||
connector, err := stmt.NewConnector(config)
|
connector, err := stmt.NewConnector(config)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal("failed to create stmt connector, err:", err)
|
log.Fatalln("Failed to create stmt connector,url: " + taosDSN + "; ErrMessage: " + err.Error())
|
||||||
}
|
}
|
||||||
// prepare statement
|
// prepare statement
|
||||||
sql := "INSERT INTO ? USING meters TAGS(?,?) VALUES (?,?,?,?)"
|
sql := "INSERT INTO ? USING meters TAGS(?,?) VALUES (?,?,?,?)"
|
||||||
stmt, err := connector.Init()
|
stmt, err := connector.Init()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal("failed to init stmt, err:", err)
|
log.Fatalln("Failed to init stmt, url: " + taosDSN + "; ErrMessage: " + err.Error())
|
||||||
}
|
}
|
||||||
err = stmt.Prepare(sql)
|
err = stmt.Prepare(sql)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal("failed to prepare stmt, err:", err)
|
log.Fatal("Failed to prepare sql, url: " + taosDSN + "; ErrMessage: " + err.Error())
|
||||||
}
|
}
|
||||||
for i := 1; i <= numOfSubTable; i++ {
|
for i := 1; i <= numOfSubTable; i++ {
|
||||||
tableName := fmt.Sprintf("d_bind_%d", i)
|
tableName := fmt.Sprintf("d_bind_%d", i)
|
||||||
|
@ -61,12 +63,12 @@ func main() {
|
||||||
// set tableName
|
// set tableName
|
||||||
err = stmt.SetTableName(tableName)
|
err = stmt.SetTableName(tableName)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal("failed to set table name, err:", err)
|
log.Fatal("Failed to set table name, url: " + taosDSN + "; ErrMessage: " + err.Error())
|
||||||
}
|
}
|
||||||
// set tags
|
// set tags
|
||||||
err = stmt.SetTags(tags, tagsType)
|
err = stmt.SetTags(tags, tagsType)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal("failed to set tags, err:", err)
|
log.Fatal("Failed to set tags, url: " + taosDSN + "; ErrMessage: " + err.Error())
|
||||||
}
|
}
|
||||||
// bind column data
|
// bind column data
|
||||||
current := time.Now()
|
current := time.Now()
|
||||||
|
@ -78,26 +80,26 @@ func main() {
|
||||||
columnData[3] = param.NewParam(1).AddFloat(rand.Float32())
|
columnData[3] = param.NewParam(1).AddFloat(rand.Float32())
|
||||||
err = stmt.BindParam(columnData, columnType)
|
err = stmt.BindParam(columnData, columnType)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal("failed to bind param, err:", err)
|
log.Fatal("Failed to bind params, url: " + taosDSN + "; ErrMessage: " + err.Error())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// add batch
|
// add batch
|
||||||
err = stmt.AddBatch()
|
err = stmt.AddBatch()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal("failed to add batch, err:", err)
|
log.Fatal("Failed to add batch, url: " + taosDSN + "; ErrMessage: " + err.Error())
|
||||||
}
|
}
|
||||||
// execute batch
|
// execute batch
|
||||||
err = stmt.Exec()
|
err = stmt.Exec()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal("failed to exec stmt, err:", err)
|
log.Fatal("Failed to exec, url: " + taosDSN + "; ErrMessage: " + err.Error())
|
||||||
}
|
}
|
||||||
// get affected rows
|
// get affected rows
|
||||||
affected := stmt.GetAffectedRows()
|
affected := stmt.GetAffectedRows()
|
||||||
// you can check exeResult here
|
// you can check exeResult here
|
||||||
fmt.Printf("table %s insert %d rows.\n", tableName, affected)
|
fmt.Printf("Successfully inserted %d rows to %s.\n", affected, tableName)
|
||||||
}
|
}
|
||||||
err = stmt.Close()
|
err = stmt.Close()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal("failed to close stmt, err:", err)
|
log.Fatal("Failed to close stmt, url: " + taosDSN + "; ErrMessage: " + err.Error())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -15,9 +15,10 @@ var done = make(chan struct{})
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
// init env
|
// init env
|
||||||
conn, err := sql.Open("taosSql", "root:taosdata@tcp(127.0.0.1:6030)/")
|
taosDSN := "root:taosdata@tcp(127.0.0.1:6030)/"
|
||||||
|
conn, err := sql.Open("taosSql", taosDSN)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal("failed to connect TDengine, err:", err)
|
log.Fatalln("Failed to connect to " + taosDSN + "; ErrMessage: " + err.Error())
|
||||||
}
|
}
|
||||||
defer func() {
|
defer func() {
|
||||||
conn.Close()
|
conn.Close()
|
||||||
|
@ -25,6 +26,9 @@ func main() {
|
||||||
initEnv(conn)
|
initEnv(conn)
|
||||||
// ANCHOR: create_consumer
|
// ANCHOR: create_consumer
|
||||||
// create consumer
|
// create consumer
|
||||||
|
groupID := "group1"
|
||||||
|
clientID := "client1"
|
||||||
|
host := "127.0.0.1"
|
||||||
consumer, err := tmq.NewConsumer(&tmqcommon.ConfigMap{
|
consumer, err := tmq.NewConsumer(&tmqcommon.ConfigMap{
|
||||||
"td.connect.user": "root",
|
"td.connect.user": "root",
|
||||||
"td.connect.pass": "taosdata",
|
"td.connect.pass": "taosdata",
|
||||||
|
@ -32,18 +36,21 @@ func main() {
|
||||||
"msg.with.table.name": "true",
|
"msg.with.table.name": "true",
|
||||||
"enable.auto.commit": "true",
|
"enable.auto.commit": "true",
|
||||||
"auto.commit.interval.ms": "1000",
|
"auto.commit.interval.ms": "1000",
|
||||||
"group.id": "group1",
|
"group.id": groupID,
|
||||||
"client.id": "client1",
|
"client.id": clientID,
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal("failed to create consumer, err:", err)
|
log.Fatalln("Failed to create native consumer, host : " + host + "; ErrMessage: " + err.Error())
|
||||||
}
|
}
|
||||||
|
log.Println("Create consumer successfully, host: " + host + ", groupId: " + groupID + ", clientId: " + clientID)
|
||||||
|
|
||||||
// ANCHOR_END: create_consumer
|
// ANCHOR_END: create_consumer
|
||||||
// ANCHOR: subscribe
|
// ANCHOR: subscribe
|
||||||
err = consumer.Subscribe("topic_meters", nil)
|
err = consumer.Subscribe("topic_meters", nil)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal("failed to subscribe, err:", err)
|
log.Fatalln("Failed to subscribe, host : " + host + "; ErrMessage: " + err.Error())
|
||||||
}
|
}
|
||||||
|
log.Println("Subscribe topics successfully")
|
||||||
for i := 0; i < 50; i++ {
|
for i := 0; i < 50; i++ {
|
||||||
ev := consumer.Poll(100)
|
ev := consumer.Poll(100)
|
||||||
if ev != nil {
|
if ev != nil {
|
||||||
|
@ -53,23 +60,16 @@ func main() {
|
||||||
fmt.Printf("data:%v\n", e)
|
fmt.Printf("data:%v\n", e)
|
||||||
// ANCHOR: commit_offset
|
// ANCHOR: commit_offset
|
||||||
// commit offset
|
// commit offset
|
||||||
topicPartition, err := consumer.CommitOffsets([]tmqcommon.TopicPartition{e.TopicPartition})
|
_, err = consumer.CommitOffsets([]tmqcommon.TopicPartition{e.TopicPartition})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal("failed to commit offset, err:", err)
|
log.Fatalln("Failed to commit offset, host : " + host + "; ErrMessage: " + err.Error())
|
||||||
}
|
}
|
||||||
fmt.Println(topicPartition)
|
log.Println("Commit offset manually successfully.")
|
||||||
// ANCHOR_END: commit_offset
|
// ANCHOR_END: commit_offset
|
||||||
case tmqcommon.Error:
|
case tmqcommon.Error:
|
||||||
fmt.Printf("%% Error: %v: %v\n", e.Code(), e)
|
fmt.Printf("%% Error: %v: %v\n", e.Code(), e)
|
||||||
log.Fatal("failed to get message, err:", e)
|
log.Fatalln("Failed to poll data, host : " + host + "; ErrMessage: " + err.Error())
|
||||||
}
|
}
|
||||||
// commit all offsets
|
|
||||||
topicPartition, err := consumer.Commit()
|
|
||||||
if err != nil {
|
|
||||||
log.Fatal("failed to commit, err:", err)
|
|
||||||
}
|
|
||||||
fmt.Println(topicPartition)
|
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// ANCHOR_END: subscribe
|
// ANCHOR_END: subscribe
|
||||||
|
@ -77,10 +77,10 @@ func main() {
|
||||||
// get assignment
|
// get assignment
|
||||||
partitions, err := consumer.Assignment()
|
partitions, err := consumer.Assignment()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal("failed to get assignment, err:", err)
|
log.Fatal("Failed to get assignment; ErrMessage: " + err.Error())
|
||||||
}
|
}
|
||||||
|
fmt.Println("Now assignment:", partitions)
|
||||||
for i := 0; i < len(partitions); i++ {
|
for i := 0; i < len(partitions); i++ {
|
||||||
fmt.Println(partitions[i])
|
|
||||||
// seek to the beginning
|
// seek to the beginning
|
||||||
err = consumer.Seek(tmqcommon.TopicPartition{
|
err = consumer.Seek(tmqcommon.TopicPartition{
|
||||||
Topic: partitions[i].Topic,
|
Topic: partitions[i].Topic,
|
||||||
|
@ -88,40 +88,21 @@ func main() {
|
||||||
Offset: 0,
|
Offset: 0,
|
||||||
}, 0)
|
}, 0)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal("failed to seek, err:", err)
|
log.Fatalln("Seek example failed; ErrMessage: " + err.Error())
|
||||||
}
|
|
||||||
}
|
|
||||||
fmt.Println("assignment seek to beginning successfully")
|
|
||||||
// poll data again
|
|
||||||
gotData := false
|
|
||||||
for i := 0; i < 50; i++ {
|
|
||||||
if gotData {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
ev := consumer.Poll(100)
|
|
||||||
if ev != nil {
|
|
||||||
switch e := ev.(type) {
|
|
||||||
case *tmqcommon.DataMessage:
|
|
||||||
// process your data here
|
|
||||||
fmt.Printf("second data polled:%v\n", e)
|
|
||||||
gotData = true
|
|
||||||
case tmqcommon.Error:
|
|
||||||
fmt.Printf("%% Error: %v: %v\n", e.Code(), e)
|
|
||||||
log.Fatal("failed to get message, err:", e)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
fmt.Println("Assignment seek to beginning successfully")
|
||||||
// ANCHOR_END: seek
|
// ANCHOR_END: seek
|
||||||
// ANCHOR: close
|
// ANCHOR: close
|
||||||
// unsubscribe
|
// unsubscribe
|
||||||
err = consumer.Unsubscribe()
|
err = consumer.Unsubscribe()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal("failed to unsubscribe, err:", err)
|
log.Fatal("Failed to unsubscribe consumer. ErrMessage: " + err.Error())
|
||||||
}
|
}
|
||||||
// close consumer
|
// close consumer
|
||||||
err = consumer.Close()
|
err = consumer.Close()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal("failed to close consumer, err:", err)
|
log.Fatal("Failed to close consumer. ErrMessage: " + err.Error())
|
||||||
}
|
}
|
||||||
// ANCHOR_END: close
|
// ANCHOR_END: close
|
||||||
<-done
|
<-done
|
||||||
|
@ -130,22 +111,22 @@ func main() {
|
||||||
func initEnv(conn *sql.DB) {
|
func initEnv(conn *sql.DB) {
|
||||||
_, err := conn.Exec("CREATE DATABASE IF NOT EXISTS power")
|
_, err := conn.Exec("CREATE DATABASE IF NOT EXISTS power")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal("failed to create database, err:", err)
|
log.Fatal("Failed to create database. ErrMessage: " + err.Error())
|
||||||
}
|
}
|
||||||
_, err = conn.Exec("CREATE STABLE IF NOT EXISTS power.meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (groupId INT, location BINARY(24))")
|
_, err = conn.Exec("CREATE STABLE IF NOT EXISTS power.meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (groupId INT, location BINARY(24))")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal("failed to create stable, err:", err)
|
log.Fatal("Failed to create stable. ErrMessage: " + err.Error())
|
||||||
}
|
}
|
||||||
_, err = conn.Exec("CREATE TOPIC IF NOT EXISTS topic_meters AS SELECT ts, current, voltage, phase, groupid, location FROM power.meters")
|
_, err = conn.Exec("CREATE TOPIC IF NOT EXISTS topic_meters AS SELECT ts, current, voltage, phase, groupid, location FROM power.meters")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal("failed to create topic, err:", err)
|
log.Fatal("Failed to create topic. ErrMessage: " + err.Error())
|
||||||
}
|
}
|
||||||
go func() {
|
go func() {
|
||||||
for i := 0; i < 10; i++ {
|
for i := 0; i < 10; i++ {
|
||||||
time.Sleep(time.Second)
|
time.Sleep(time.Second)
|
||||||
_, err = conn.Exec("INSERT INTO power.d1001 USING power.meters TAGS (2, 'California.SanFrancisco') VALUES (NOW , 10.2, 219, 0.32)")
|
_, err = conn.Exec("INSERT INTO power.d1001 USING power.meters TAGS (2, 'California.SanFrancisco') VALUES (NOW , 10.2, 219, 0.32)")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal("failed to insert data, err:", err)
|
log.Fatal("Failed to insert data. ErrMessage: " + err.Error())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
done <- struct{}{}
|
done <- struct{}{}
|
||||||
|
|
|
@ -16,9 +16,10 @@ var done = make(chan struct{})
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
// init env
|
// init env
|
||||||
conn, err := sql.Open("taosWS", "root:taosdata@ws(127.0.0.1:6041)/")
|
taosDSN := "root:taosdata@ws(127.0.0.1:6041)/"
|
||||||
|
conn, err := sql.Open("taosWS", taosDSN)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal("failed to connect TDengine, err:", err)
|
log.Fatalln("Failed to connect to " + taosDSN + "; ErrMessage: " + err.Error())
|
||||||
}
|
}
|
||||||
defer func() {
|
defer func() {
|
||||||
conn.Close()
|
conn.Close()
|
||||||
|
@ -26,8 +27,11 @@ func main() {
|
||||||
initEnv(conn)
|
initEnv(conn)
|
||||||
// ANCHOR: create_consumer
|
// ANCHOR: create_consumer
|
||||||
// create consumer
|
// create consumer
|
||||||
|
wsUrl := "ws://127.0.0.1:6041"
|
||||||
|
groupID := "group1"
|
||||||
|
clientID := "client1"
|
||||||
consumer, err := tmq.NewConsumer(&tmqcommon.ConfigMap{
|
consumer, err := tmq.NewConsumer(&tmqcommon.ConfigMap{
|
||||||
"ws.url": "ws://127.0.0.1:6041",
|
"ws.url": wsUrl,
|
||||||
"ws.message.channelLen": uint(0),
|
"ws.message.channelLen": uint(0),
|
||||||
"ws.message.timeout": common.DefaultMessageTimeout,
|
"ws.message.timeout": common.DefaultMessageTimeout,
|
||||||
"ws.message.writeWait": common.DefaultWriteWait,
|
"ws.message.writeWait": common.DefaultWriteWait,
|
||||||
|
@ -37,18 +41,21 @@ func main() {
|
||||||
"msg.with.table.name": "true",
|
"msg.with.table.name": "true",
|
||||||
"enable.auto.commit": "true",
|
"enable.auto.commit": "true",
|
||||||
"auto.commit.interval.ms": "1000",
|
"auto.commit.interval.ms": "1000",
|
||||||
"group.id": "group1",
|
"group.id": groupID,
|
||||||
"client.id": "client1",
|
"client.id": clientID,
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal("failed to create consumer, err:", err)
|
log.Fatalln("Failed to create websocket consumer, host : " + wsUrl + "; ErrMessage: " + err.Error())
|
||||||
}
|
}
|
||||||
|
log.Println("Create consumer successfully, host: " + wsUrl + ", groupId: " + groupID + ", clientId: " + clientID)
|
||||||
|
|
||||||
// ANCHOR_END: create_consumer
|
// ANCHOR_END: create_consumer
|
||||||
// ANCHOR: subscribe
|
// ANCHOR: subscribe
|
||||||
err = consumer.Subscribe("topic_meters", nil)
|
err = consumer.Subscribe("topic_meters", nil)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal("failed to subscribe, err:", err)
|
log.Fatalln("Failed to subscribe, host : " + wsUrl + "; ErrMessage: " + err.Error())
|
||||||
}
|
}
|
||||||
|
log.Println("Subscribe topics successfully")
|
||||||
for i := 0; i < 50; i++ {
|
for i := 0; i < 50; i++ {
|
||||||
ev := consumer.Poll(100)
|
ev := consumer.Poll(100)
|
||||||
if ev != nil {
|
if ev != nil {
|
||||||
|
@ -58,23 +65,16 @@ func main() {
|
||||||
fmt.Printf("data:%v\n", e)
|
fmt.Printf("data:%v\n", e)
|
||||||
// ANCHOR: commit_offset
|
// ANCHOR: commit_offset
|
||||||
// commit offset
|
// commit offset
|
||||||
topicPartition, err := consumer.CommitOffsets([]tmqcommon.TopicPartition{e.TopicPartition})
|
_, err = consumer.CommitOffsets([]tmqcommon.TopicPartition{e.TopicPartition})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal("failed to commit offset, err:", err)
|
log.Fatalln("Failed to commit offset, host : " + wsUrl + "; ErrMessage: " + err.Error())
|
||||||
}
|
}
|
||||||
fmt.Println(topicPartition)
|
log.Println("Commit offset manually successfully.")
|
||||||
// ANCHOR_END: commit_offset
|
// ANCHOR_END: commit_offset
|
||||||
case tmqcommon.Error:
|
case tmqcommon.Error:
|
||||||
fmt.Printf("%% Error: %v: %v\n", e.Code(), e)
|
fmt.Printf("%% Error: %v: %v\n", e.Code(), e)
|
||||||
log.Fatal("failed to get message, err:", e)
|
log.Fatalln("Failed to poll data, host : " + wsUrl + "; ErrMessage: " + err.Error())
|
||||||
}
|
}
|
||||||
// commit all offsets
|
|
||||||
topicPartition, err := consumer.Commit()
|
|
||||||
if err != nil {
|
|
||||||
log.Fatal("failed to commit, err:", err)
|
|
||||||
}
|
|
||||||
fmt.Println(topicPartition)
|
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// ANCHOR_END: subscribe
|
// ANCHOR_END: subscribe
|
||||||
|
@ -82,10 +82,10 @@ func main() {
|
||||||
// get assignment
|
// get assignment
|
||||||
partitions, err := consumer.Assignment()
|
partitions, err := consumer.Assignment()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal("failed to get assignment, err:", err)
|
log.Fatal("Failed to get assignment; ErrMessage: " + err.Error())
|
||||||
}
|
}
|
||||||
|
fmt.Println("Now assignment:", partitions)
|
||||||
for i := 0; i < len(partitions); i++ {
|
for i := 0; i < len(partitions); i++ {
|
||||||
fmt.Println(partitions[i])
|
|
||||||
// seek to the beginning
|
// seek to the beginning
|
||||||
err = consumer.Seek(tmqcommon.TopicPartition{
|
err = consumer.Seek(tmqcommon.TopicPartition{
|
||||||
Topic: partitions[i].Topic,
|
Topic: partitions[i].Topic,
|
||||||
|
@ -93,40 +93,21 @@ func main() {
|
||||||
Offset: 0,
|
Offset: 0,
|
||||||
}, 0)
|
}, 0)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal("failed to seek, err:", err)
|
log.Fatalln("Seek example failed; ErrMessage: " + err.Error())
|
||||||
}
|
|
||||||
}
|
|
||||||
fmt.Println("assignment seek to beginning successfully")
|
|
||||||
// poll data again
|
|
||||||
gotData := false
|
|
||||||
for i := 0; i < 50; i++ {
|
|
||||||
if gotData {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
ev := consumer.Poll(100)
|
|
||||||
if ev != nil {
|
|
||||||
switch e := ev.(type) {
|
|
||||||
case *tmqcommon.DataMessage:
|
|
||||||
// process your data here
|
|
||||||
fmt.Printf("second data polled:%v\n", e)
|
|
||||||
gotData = true
|
|
||||||
case tmqcommon.Error:
|
|
||||||
fmt.Printf("%% Error: %v: %v\n", e.Code(), e)
|
|
||||||
log.Fatal("failed to get message, err:", e)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
fmt.Println("Assignment seek to beginning successfully")
|
||||||
// ANCHOR_END: seek
|
// ANCHOR_END: seek
|
||||||
// ANCHOR: close
|
// ANCHOR: close
|
||||||
// unsubscribe
|
// unsubscribe
|
||||||
err = consumer.Unsubscribe()
|
err = consumer.Unsubscribe()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal("failed to unsubscribe, err:", err)
|
log.Fatal("Failed to unsubscribe consumer. ErrMessage: " + err.Error())
|
||||||
}
|
}
|
||||||
// close consumer
|
// close consumer
|
||||||
err = consumer.Close()
|
err = consumer.Close()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal("failed to close consumer, err:", err)
|
log.Fatal("Failed to close consumer. ErrMessage: " + err.Error())
|
||||||
}
|
}
|
||||||
// ANCHOR_END: close
|
// ANCHOR_END: close
|
||||||
<-done
|
<-done
|
||||||
|
@ -135,22 +116,22 @@ func main() {
|
||||||
func initEnv(conn *sql.DB) {
|
func initEnv(conn *sql.DB) {
|
||||||
_, err := conn.Exec("CREATE DATABASE IF NOT EXISTS power")
|
_, err := conn.Exec("CREATE DATABASE IF NOT EXISTS power")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal("failed to create database, err:", err)
|
log.Fatal("Failed to create database. ErrMessage: " + err.Error())
|
||||||
}
|
}
|
||||||
_, err = conn.Exec("CREATE STABLE IF NOT EXISTS power.meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (groupId INT, location BINARY(24))")
|
_, err = conn.Exec("CREATE STABLE IF NOT EXISTS power.meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (groupId INT, location BINARY(24))")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal("failed to create stable, err:", err)
|
log.Fatal("Failed to create stable. ErrMessage: " + err.Error())
|
||||||
}
|
}
|
||||||
_, err = conn.Exec("CREATE TOPIC IF NOT EXISTS topic_meters AS SELECT ts, current, voltage, phase, groupid, location FROM power.meters")
|
_, err = conn.Exec("CREATE TOPIC IF NOT EXISTS topic_meters AS SELECT ts, current, voltage, phase, groupid, location FROM power.meters")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal("failed to create topic, err:", err)
|
log.Fatal("Failed to create topic. ErrMessage: " + err.Error())
|
||||||
}
|
}
|
||||||
go func() {
|
go func() {
|
||||||
for i := 0; i < 10; i++ {
|
for i := 0; i < 10; i++ {
|
||||||
time.Sleep(time.Second)
|
time.Sleep(time.Second)
|
||||||
_, err = conn.Exec("INSERT INTO power.d1001 USING power.meters TAGS (2, 'California.SanFrancisco') VALUES (NOW , 10.2, 219, 0.32)")
|
_, err = conn.Exec("INSERT INTO power.d1001 USING power.meters TAGS (2, 'California.SanFrancisco') VALUES (NOW , 10.2, 219, 0.32)")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal("failed to insert data, err:", err)
|
log.Fatal("Failed to insert data. ErrMessage: " + err.Error())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
done <- struct{}{}
|
done <- struct{}{}
|
||||||
|
|
|
@ -16,6 +16,7 @@ async function createConnect() {
|
||||||
}
|
}
|
||||||
|
|
||||||
async function test() {
|
async function test() {
|
||||||
|
let dsn = 'ws://localhost:6041'
|
||||||
let wsSql = null;
|
let wsSql = null;
|
||||||
let wsRows = null;
|
let wsRows = null;
|
||||||
let ttl = 0;
|
let ttl = 0;
|
||||||
|
@ -24,9 +25,10 @@ async function test() {
|
||||||
await wsSql.schemalessInsert(influxdbData, taos.SchemalessProto.InfluxDBLineProtocol, taos.Precision.MILLI_SECONDS, ttl);
|
await wsSql.schemalessInsert(influxdbData, taos.SchemalessProto.InfluxDBLineProtocol, taos.Precision.MILLI_SECONDS, ttl);
|
||||||
await wsSql.schemalessInsert(telnetData, taos.SchemalessProto.OpenTSDBTelnetLineProtocol, taos.Precision.MILLI_SECONDS, ttl);
|
await wsSql.schemalessInsert(telnetData, taos.SchemalessProto.OpenTSDBTelnetLineProtocol, taos.Precision.MILLI_SECONDS, ttl);
|
||||||
await wsSql.schemalessInsert(jsonData, taos.SchemalessProto.OpenTSDBJsonFormatProtocol, taos.Precision.SECONDS, ttl);
|
await wsSql.schemalessInsert(jsonData, taos.SchemalessProto.OpenTSDBJsonFormatProtocol, taos.Precision.SECONDS, ttl);
|
||||||
|
console.log("Inserted data with schemaless successfully.")
|
||||||
}
|
}
|
||||||
catch (err) {
|
catch (err) {
|
||||||
console.error("Failed to insert data with schemaless, ErrCode:" + err.code + "; ErrMessage: " + err.message);
|
console.error("Failed to insert data with schemaless, url:"+ dsn +", ErrCode:" + err.code + "; ErrMessage: " + err.message);
|
||||||
}
|
}
|
||||||
finally {
|
finally {
|
||||||
if (wsRows) {
|
if (wsRows) {
|
||||||
|
|
|
@ -1,34 +1,41 @@
|
||||||
// ANCHOR: createConnect
|
// ANCHOR: createConnect
|
||||||
const taos = require("@tdengine/websocket");
|
const taos = require("@tdengine/websocket");
|
||||||
|
|
||||||
|
let dsn = 'ws://localhost:6041';
|
||||||
async function createConnect() {
|
async function createConnect() {
|
||||||
let dsn = 'ws://localhost:6041';
|
|
||||||
let conf = new taos.WSConfig(dsn);
|
try {
|
||||||
conf.setUser('root');
|
let conf = new taos.WSConfig(dsn);
|
||||||
conf.setPwd('taosdata');
|
conf.setUser('root');
|
||||||
conf.setDb('power');
|
conf.setPwd('taosdata');
|
||||||
return await taos.sqlConnect(conf);
|
conf.setDb('power');
|
||||||
|
conn = await taos.sqlConnect(conf);
|
||||||
|
console.log("Connected to " + dsn + " successfully.");
|
||||||
|
return conn;
|
||||||
|
} catch (err) {
|
||||||
|
console.log("Failed to connect to " + dns + "; ErrCode:" + err.code + "; ErrMessage: " + err.message);
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
// ANCHOR_END: createConnect
|
// ANCHOR_END: createConnect
|
||||||
|
|
||||||
// ANCHOR: create_db_and_table
|
// ANCHOR: create_db_and_table
|
||||||
async function createDbAndTable(wsSql) {
|
async function createDbAndTable() {
|
||||||
let wsSql = null;
|
let wsSql = null;
|
||||||
try {
|
try {
|
||||||
wsSql = await createConnect();
|
wsSql = await createConnect();
|
||||||
await wsSql.exec('CREATE DATABASE IF NOT EXISTS POWER ' +
|
// create database
|
||||||
'KEEP 3650 DURATION 10 BUFFER 16 WAL_LEVEL 1;');
|
await wsSql.exec('CREATE DATABASE IF NOT EXISTS power');
|
||||||
|
console.log("Create database power successfully.");
|
||||||
await wsSql.exec('USE power');
|
// create table
|
||||||
|
await wsSql.exec('CREATE STABLE IF NOT EXISTS power.meters ' +
|
||||||
await wsSql.exec('CREATE STABLE IF NOT EXISTS meters ' +
|
|
||||||
'(_ts timestamp, current float, voltage int, phase float) ' +
|
'(_ts timestamp, current float, voltage int, phase float) ' +
|
||||||
'TAGS (location binary(64), groupId int);');
|
'TAGS (location binary(64), groupId int);');
|
||||||
|
|
||||||
taosResult = await wsSql.exec('describe meters');
|
console.log("Create stable power.meters successfully");
|
||||||
console.log(taosResult);
|
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error("Failed to create db and table, ErrCode:" + err.code + "; ErrMessage: " + err.message);
|
console.error("Failed to create db and table, url:" + dns + "; ErrCode:" + err.code + "; ErrMessage: " + err.message);
|
||||||
} finally {
|
} finally {
|
||||||
if (wsSql) {
|
if (wsSql) {
|
||||||
await wsSql.close();
|
await wsSql.close();
|
||||||
|
@ -39,8 +46,8 @@ async function createDbAndTable(wsSql) {
|
||||||
// ANCHOR_END: create_db_and_table
|
// ANCHOR_END: create_db_and_table
|
||||||
|
|
||||||
// ANCHOR: insertData
|
// ANCHOR: insertData
|
||||||
async function insertData(wsSql) {
|
async function insertData() {
|
||||||
let wsSql = null;
|
let wsSql = null
|
||||||
try {
|
try {
|
||||||
wsSql = await createConnect();
|
wsSql = await createConnect();
|
||||||
let insertQuery = "INSERT INTO " +
|
let insertQuery = "INSERT INTO " +
|
||||||
|
@ -53,9 +60,9 @@ async function insertData(wsSql) {
|
||||||
"VALUES " +
|
"VALUES " +
|
||||||
"(NOW + 1a, 10.30000, 218, 0.25000) ";
|
"(NOW + 1a, 10.30000, 218, 0.25000) ";
|
||||||
taosResult = await wsSql.exec(insertQuery);
|
taosResult = await wsSql.exec(insertQuery);
|
||||||
console.log(taosResult);
|
console.log("Successfully inserted " + taosResult.getAffectRows() + " rows to power.meters.");
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error("Failed to insert data to power.meters, ErrCode:" + err.code + "; ErrMessage: " + err.message);
|
console.error("Failed to insert data to power.meters, url:" + dsn + "; ErrCode:" + err.code + "; ErrMessage: " + err.message);
|
||||||
} finally {
|
} finally {
|
||||||
if (wsSql) {
|
if (wsSql) {
|
||||||
await wsSql.close();
|
await wsSql.close();
|
||||||
|
@ -71,15 +78,13 @@ async function queryData() {
|
||||||
try {
|
try {
|
||||||
wsSql = await createConnect();
|
wsSql = await createConnect();
|
||||||
wsRows = await wsSql.query('SELECT ts, current, location FROM power.meters limit 100');
|
wsRows = await wsSql.query('SELECT ts, current, location FROM power.meters limit 100');
|
||||||
let meta = wsRows.getMeta();
|
|
||||||
console.log("wsRow:meta:=>", meta);
|
|
||||||
while (await wsRows.next()) {
|
while (await wsRows.next()) {
|
||||||
let result = wsRows.getData();
|
let row = wsRows.getData();
|
||||||
console.log('queryRes.Scan().then=>', result);
|
console.log('ts: ' + row[0] + ', current: ' + row[1] + ', location: ' + row[2]);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
catch (err) {
|
catch (err) {
|
||||||
console.error("Failed to query data from power.meters," + err.code + "; ErrMessage: " + err.message);
|
console.error("Failed to query data from power.meters, url:" + dsn + " ; ErrCode:" + err.code + "; ErrMessage: " + err.message);
|
||||||
}
|
}
|
||||||
finally {
|
finally {
|
||||||
if (wsRows) {
|
if (wsRows) {
|
||||||
|
@ -93,22 +98,20 @@ async function queryData() {
|
||||||
// ANCHOR_END: queryData
|
// ANCHOR_END: queryData
|
||||||
|
|
||||||
// ANCHOR: sqlWithReqid
|
// ANCHOR: sqlWithReqid
|
||||||
async function sqlWithReqid(wsSql) {
|
async function sqlWithReqid() {
|
||||||
|
|
||||||
let wsRows = null;
|
let wsRows = null;
|
||||||
let wsSql = null;
|
let wsSql = null;
|
||||||
|
let reqId = 1;
|
||||||
try {
|
try {
|
||||||
wsSql = await createConnect();
|
wsSql = await createConnect();
|
||||||
wsRows = await wsSql.query('SELECT ts, current, location FROM power.meters limit 100', 1);
|
wsRows = await wsSql.query('SELECT ts, current, location FROM power.meters limit 100', reqId);
|
||||||
let meta = wsRows.getMeta();
|
|
||||||
console.log("wsRow:meta:=>", meta);
|
|
||||||
while (await wsRows.next()) {
|
while (await wsRows.next()) {
|
||||||
let result = wsRows.getData();
|
let row = wsRows.getData();
|
||||||
console.log('queryRes.Scan().then=>', result);
|
console.log('ts: ' + row[0] + ', current: ' + row[1] + ', location: ' + row[2]);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
catch (err) {
|
catch (err) {
|
||||||
console.error("Failed to execute sql with reqId," + err.code + "; ErrMessage: " + err.message);
|
console.error("Failed to execute sql with reqId: " + reqId + ", ErrCode:" + err.code + "; ErrMessage: " + err.message);
|
||||||
}
|
}
|
||||||
finally {
|
finally {
|
||||||
if (wsRows) {
|
if (wsRows) {
|
||||||
|
|
|
@ -3,7 +3,8 @@ const taos = require("@tdengine/websocket");
|
||||||
let db = 'power';
|
let db = 'power';
|
||||||
let stable = 'meters';
|
let stable = 'meters';
|
||||||
let numOfSubTable = 10;
|
let numOfSubTable = 10;
|
||||||
let numOfRow = 10;
|
let numOfRow = 10;
|
||||||
|
let dsn = 'ws://localhost:6041'
|
||||||
function getRandomInt(min, max) {
|
function getRandomInt(min, max) {
|
||||||
min = Math.ceil(min);
|
min = Math.ceil(min);
|
||||||
max = Math.floor(max);
|
max = Math.floor(max);
|
||||||
|
@ -11,7 +12,7 @@ function getRandomInt(min, max) {
|
||||||
}
|
}
|
||||||
|
|
||||||
async function prepare() {
|
async function prepare() {
|
||||||
let dsn = 'ws://localhost:6041'
|
|
||||||
let conf = new taos.WSConfig(dsn);
|
let conf = new taos.WSConfig(dsn);
|
||||||
conf.setUser('root')
|
conf.setUser('root')
|
||||||
conf.setPwd('taosdata')
|
conf.setPwd('taosdata')
|
||||||
|
@ -54,11 +55,11 @@ async function prepare() {
|
||||||
await stmt.bind(bindParams);
|
await stmt.bind(bindParams);
|
||||||
await stmt.batch();
|
await stmt.batch();
|
||||||
await stmt.exec();
|
await stmt.exec();
|
||||||
console.log(`d_bind_${i} insert ` + stmt.getLastAffected() + " rows.");
|
console.log("Successfully inserted " + stmt.getLastAffected() + " to power.meters.");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
catch (err) {
|
catch (err) {
|
||||||
console.error("Failed to insert to table meters using stmt, ErrCode:" + err.code + "; ErrMessage: " + err.message);
|
console.error("Failed to insert to table meters using stmt, url:" + dsn + "ErrCode:" + err.code + "; ErrMessage: " + err.message);
|
||||||
}
|
}
|
||||||
finally {
|
finally {
|
||||||
if (stmt) {
|
if (stmt) {
|
||||||
|
|
|
@ -1,23 +1,28 @@
|
||||||
const taos = require("@tdengine/websocket");
|
const taos = require("@tdengine/websocket");
|
||||||
|
|
||||||
|
// ANCHOR: create_consumer
|
||||||
const db = 'power';
|
const db = 'power';
|
||||||
const stable = 'meters';
|
const stable = 'meters';
|
||||||
const topics = ['power_meters_topic'];
|
const topics = ['power_meters_topic'];
|
||||||
|
const url = 'ws://localhost:6041';
|
||||||
// ANCHOR: create_consumer
|
|
||||||
async function createConsumer() {
|
async function createConsumer() {
|
||||||
|
|
||||||
|
let groupId = "group1";
|
||||||
|
let clientId = "1";
|
||||||
let configMap = new Map([
|
let configMap = new Map([
|
||||||
[taos.TMQConstants.GROUP_ID, "group1"],
|
[taos.TMQConstants.GROUP_ID, groupId],
|
||||||
[taos.TMQConstants.CLIENT_ID, 'client1'],
|
[taos.TMQConstants.CLIENT_ID, clientId],
|
||||||
[taos.TMQConstants.CONNECT_USER, "root"],
|
[taos.TMQConstants.CONNECT_USER, "root"],
|
||||||
[taos.TMQConstants.CONNECT_PASS, "taosdata"],
|
[taos.TMQConstants.CONNECT_PASS, "taosdata"],
|
||||||
[taos.TMQConstants.AUTO_OFFSET_RESET, "latest"],
|
[taos.TMQConstants.AUTO_OFFSET_RESET, "latest"],
|
||||||
[taos.TMQConstants.WS_URL, 'ws://localhost:6041'],
|
[taos.TMQConstants.WS_URL, url],
|
||||||
[taos.TMQConstants.ENABLE_AUTO_COMMIT, 'true'],
|
[taos.TMQConstants.ENABLE_AUTO_COMMIT, 'true'],
|
||||||
[taos.TMQConstants.AUTO_COMMIT_INTERVAL_MS, '1000']
|
[taos.TMQConstants.AUTO_COMMIT_INTERVAL_MS, '1000']
|
||||||
]);
|
]);
|
||||||
try {
|
try {
|
||||||
return await taos.tmqConnect(configMap);
|
conn = await taos.tmqConnect(configMap);
|
||||||
|
console.log(`Create consumer successfully, host: ${url}, groupId: ${groupId}, clientId: ${clientId}`)
|
||||||
|
return conn;
|
||||||
}catch (err) {
|
}catch (err) {
|
||||||
console.log("Failed to create websocket consumer, ErrCode:" + err.code + "; ErrMessage: " + err.message);
|
console.log("Failed to create websocket consumer, ErrCode:" + err.code + "; ErrMessage: " + err.message);
|
||||||
throw err;
|
throw err;
|
||||||
|
@ -31,7 +36,7 @@ async function prepare() {
|
||||||
conf.setUser('root');
|
conf.setUser('root');
|
||||||
conf.setPwd('taosdata');
|
conf.setPwd('taosdata');
|
||||||
conf.setDb('power');
|
conf.setDb('power');
|
||||||
const createDB = `CREATE DATABASE IF NOT EXISTS POWER ${db} KEEP 3650 DURATION 10 BUFFER 16 WAL_LEVEL 1;`;
|
const createDB = `CREATE DATABASE IF NOT EXISTS ${db}`;
|
||||||
const createStable = `CREATE STABLE IF NOT EXISTS ${db}.${stable} (ts timestamp, current float, voltage int, phase float) TAGS (location binary(64), groupId int);`;
|
const createStable = `CREATE STABLE IF NOT EXISTS ${db}.${stable} (ts timestamp, current float, voltage int, phase float) TAGS (location binary(64), groupId int);`;
|
||||||
|
|
||||||
let wsSql = await taos.sqlConnect(conf);
|
let wsSql = await taos.sqlConnect(conf);
|
||||||
|
@ -45,7 +50,7 @@ async function prepare() {
|
||||||
for (let i = 0; i < 10; i++) {
|
for (let i = 0; i < 10; i++) {
|
||||||
await wsSql.exec(`INSERT INTO d1001 USING ${stable} (location, groupId) TAGS ("California.SanFrancisco", 3) VALUES (NOW, ${10 + i}, ${200 + i}, ${0.32 + i})`);
|
await wsSql.exec(`INSERT INTO d1001 USING ${stable} (location, groupId) TAGS ("California.SanFrancisco", 3) VALUES (NOW, ${10 + i}, ${200 + i}, ${0.32 + i})`);
|
||||||
}
|
}
|
||||||
wsSql.Close();
|
wsSql.close();
|
||||||
}
|
}
|
||||||
|
|
||||||
async function subscribe(consumer) {
|
async function subscribe(consumer) {
|
||||||
|
@ -55,12 +60,13 @@ async function subscribe(consumer) {
|
||||||
for (let i = 0; i < 50; i++) {
|
for (let i = 0; i < 50; i++) {
|
||||||
let res = await consumer.poll(100);
|
let res = await consumer.poll(100);
|
||||||
for (let [key, value] of res) {
|
for (let [key, value] of res) {
|
||||||
console.log(key, value);
|
console.log(`data: ${key} ${value}`);
|
||||||
}
|
}
|
||||||
consumer.commit();
|
consumer.commit();
|
||||||
|
console.log("Commit offset manually successfully.");
|
||||||
}
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error("Failed to poll data; err.code, ErrCode:" + err.code + "; ErrMessage: " + err.message);
|
console.error("Failed to poll data; ErrCode:" + err.code + "; ErrMessage: " + err.message);
|
||||||
throw err;
|
throw err;
|
||||||
}
|
}
|
||||||
// ANCHOR_END: commit
|
// ANCHOR_END: commit
|
||||||
|
@ -74,6 +80,7 @@ async function test() {
|
||||||
let consumer = await createConsumer()
|
let consumer = await createConsumer()
|
||||||
await subscribe(consumer)
|
await subscribe(consumer)
|
||||||
await consumer.unsubscribe();
|
await consumer.unsubscribe();
|
||||||
|
console.log("Consumer unsubscribed successfully.");
|
||||||
}
|
}
|
||||||
catch (err) {
|
catch (err) {
|
||||||
console.error("Failed to unsubscribe consume, ErrCode:" + err.code + "; ErrMessage: " + err.message);
|
console.error("Failed to unsubscribe consume, ErrCode:" + err.code + "; ErrMessage: " + err.message);
|
||||||
|
|
|
@ -18,11 +18,11 @@ async function createConsumer() {
|
||||||
]);
|
]);
|
||||||
try {
|
try {
|
||||||
return await taos.tmqConnect(configMap);
|
return await taos.tmqConnect(configMap);
|
||||||
}catch (err) {
|
} catch (err) {
|
||||||
console.log(err);
|
console.log(err);
|
||||||
throw err;
|
throw err;
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
// ANCHOR_END: create_consumer
|
// ANCHOR_END: create_consumer
|
||||||
|
|
||||||
|
@ -33,7 +33,7 @@ async function prepare() {
|
||||||
conf.setDb('power');
|
conf.setDb('power');
|
||||||
const createDB = `CREATE DATABASE IF NOT EXISTS POWER ${db} KEEP 3650 DURATION 10 BUFFER 16 WAL_LEVEL 1;`;
|
const createDB = `CREATE DATABASE IF NOT EXISTS POWER ${db} KEEP 3650 DURATION 10 BUFFER 16 WAL_LEVEL 1;`;
|
||||||
const createStable = `CREATE STABLE IF NOT EXISTS ${db}.${stable} (ts timestamp, current float, voltage int, phase float) TAGS (location binary(64), groupId int);`;
|
const createStable = `CREATE STABLE IF NOT EXISTS ${db}.${stable} (ts timestamp, current float, voltage int, phase float) TAGS (location binary(64), groupId int);`;
|
||||||
|
|
||||||
let wsSql = await taos.sqlConnect(conf);
|
let wsSql = await taos.sqlConnect(conf);
|
||||||
await wsSql.exec(createDB);
|
await wsSql.exec(createDB);
|
||||||
await wsSql.exec(createStable);
|
await wsSql.exec(createStable);
|
||||||
|
@ -55,11 +55,11 @@ async function subscribe(consumer) {
|
||||||
for (let i = 0; i < 50; i++) {
|
for (let i = 0; i < 50; i++) {
|
||||||
let res = await consumer.poll(100);
|
let res = await consumer.poll(100);
|
||||||
for (let [key, value] of res) {
|
for (let [key, value] of res) {
|
||||||
console.log(key, value);
|
console.log(`data: ${key} ${value}`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}catch (err) {
|
} catch (err) {
|
||||||
console.error("Failed to poll data; err.code, ErrCode:" + err.code + "; ErrMessage: " + err.message);
|
console.error("Failed to poll data; ErrCode:" + err.code + "; ErrMessage: " + err.message);
|
||||||
throw err;
|
throw err;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -76,22 +76,14 @@ async function test() {
|
||||||
let res = new Map();
|
let res = new Map();
|
||||||
while (res.size == 0) {
|
while (res.size == 0) {
|
||||||
res = await consumer.poll(100);
|
res = await consumer.poll(100);
|
||||||
}
|
}
|
||||||
|
|
||||||
let assignment = await consumer.assignment();
|
let assignment = await consumer.assignment();
|
||||||
for (let i in assignment) {
|
|
||||||
console.log("seek before:", assignment[i]);
|
|
||||||
}
|
|
||||||
|
|
||||||
await consumer.seekToBeginning(assignment);
|
await consumer.seekToBeginning(assignment);
|
||||||
assignment = await consumer.assignment();
|
console.log("Assignment seek to beginning successfully");
|
||||||
for (let i in assignment) {
|
|
||||||
console.log("seek after:", assignment[i]);
|
|
||||||
}
|
|
||||||
await consumer.unsubscribe();
|
|
||||||
}
|
}
|
||||||
catch (err) {
|
catch (err) {
|
||||||
console.error("seek example failed, ErrCode:" + err.code + "; ErrMessage: " + err.message);
|
console.error("Seek example failed, ErrCode:" + err.code + "; ErrMessage: " + err.message);
|
||||||
}
|
}
|
||||||
finally {
|
finally {
|
||||||
if (consumer) {
|
if (consumer) {
|
||||||
|
|
|
@ -14,7 +14,7 @@ def create_connection():
|
||||||
)
|
)
|
||||||
print(f"Connected to {host}:{port} successfully.");
|
print(f"Connected to {host}:{port} successfully.");
|
||||||
except Exception as err:
|
except Exception as err:
|
||||||
print(f"Failed to connect to {host}:{port} ; Err:{err}")
|
print(f"Failed to connect to {host}:{port} ; ErrMessage:{err}")
|
||||||
finally:
|
finally:
|
||||||
if conn:
|
if conn:
|
||||||
conn.close()
|
conn.close()
|
||||||
|
|
|
@ -12,7 +12,7 @@ def create_connection():
|
||||||
|
|
||||||
print(f"Connected to {url} successfully.");
|
print(f"Connected to {url} successfully.");
|
||||||
except Exception as err:
|
except Exception as err:
|
||||||
print(f"Failed to connect to {url} ; Err:{err}")
|
print(f"Failed to connect to {url} ; ErrMessage:{err}")
|
||||||
finally:
|
finally:
|
||||||
if conn:
|
if conn:
|
||||||
conn.close()
|
conn.close()
|
||||||
|
|
|
@ -14,7 +14,7 @@ def create_connection():
|
||||||
)
|
)
|
||||||
print(f"Connected to {host}:{port} successfully.");
|
print(f"Connected to {host}:{port} successfully.");
|
||||||
except Exception as err:
|
except Exception as err:
|
||||||
print(f"Failed to connect to {host}:{port} ; Err:{err}")
|
print(f"Failed to connect to {host}:{port} ; ErrMessage:{err}")
|
||||||
|
|
||||||
return conn
|
return conn
|
||||||
# ANCHOR_END: connect
|
# ANCHOR_END: connect
|
||||||
|
|
|
@ -9,26 +9,18 @@ try:
|
||||||
user="root",
|
user="root",
|
||||||
password="taosdata")
|
password="taosdata")
|
||||||
|
|
||||||
db = "power"
|
|
||||||
# create database
|
# create database
|
||||||
rowsAffected = conn.execute(f"CREATE DATABASE IF NOT EXISTS {db}")
|
rowsAffected = conn.execute(f"CREATE DATABASE IF NOT EXISTS power")
|
||||||
assert rowsAffected == 0
|
print(f"Create database power successfully, rowsAffected: {rowsAffected}");
|
||||||
|
|
||||||
# change database. same as execute "USE db"
|
|
||||||
conn.select_db(db)
|
|
||||||
|
|
||||||
# create super table
|
# create super table
|
||||||
rowsAffected = conn.execute(
|
rowsAffected = conn.execute(
|
||||||
"CREATE TABLE IF NOT EXISTS `meters` (`ts` TIMESTAMP, `current` FLOAT, `voltage` INT, `phase` FLOAT) TAGS (`groupid` INT, `location` BINARY(16))"
|
"CREATE TABLE IF NOT EXISTS power.meters (`ts` TIMESTAMP, `current` FLOAT, `voltage` INT, `phase` FLOAT) TAGS (`groupid` INT, `location` BINARY(16))"
|
||||||
)
|
)
|
||||||
assert rowsAffected == 0
|
print(f"Create stable power.meters successfully, rowsAffected: {rowsAffected}");
|
||||||
|
|
||||||
# create table
|
|
||||||
rowsAffected = conn.execute("CREATE TABLE IF NOT EXISTS `d0` USING `meters` (groupid, location) TAGS(0, 'Los Angles')")
|
|
||||||
assert rowsAffected == 0
|
|
||||||
|
|
||||||
except Exception as err:
|
except Exception as err:
|
||||||
print(f"Failed to create db and table, db addrr:{host}:{port} err:{err}")
|
print(f"Failed to create db and table, db addr:{host}:{port} ; ErrMessage:{err}")
|
||||||
finally:
|
finally:
|
||||||
if conn:
|
if conn:
|
||||||
conn.close()
|
conn.close()
|
||||||
|
|
|
@ -8,22 +8,18 @@ try:
|
||||||
password="taosdata",
|
password="taosdata",
|
||||||
timeout=30)
|
timeout=30)
|
||||||
|
|
||||||
db = "power"
|
|
||||||
# create database
|
# create database
|
||||||
rowsAffected = conn.execute(f"CREATE DATABASE IF NOT EXISTS {db}")
|
rowsAffected = conn.execute(f"CREATE DATABASE IF NOT EXISTS power")
|
||||||
assert rowsAffected == 0
|
print(f"Create database power successfully, rowsAffected: {rowsAffected}");
|
||||||
|
|
||||||
# create super table
|
# create super table
|
||||||
rowsAffected = conn.execute(
|
rowsAffected = conn.execute(
|
||||||
f"CREATE TABLE IF NOT EXISTS `{db}`.`meters` (`ts` TIMESTAMP, `current` FLOAT, `voltage` INT, `phase` FLOAT) TAGS (`groupid` INT, `location` BINARY(16))"
|
f"CREATE TABLE IF NOT EXISTS power.meters (`ts` TIMESTAMP, `current` FLOAT, `voltage` INT, `phase` FLOAT) TAGS (`groupid` INT, `location` BINARY(16))"
|
||||||
)
|
)
|
||||||
assert rowsAffected == 0
|
print(f"Create stable power.meters successfully, rowsAffected: {rowsAffected}");
|
||||||
# create table
|
|
||||||
rowsAffected = conn.execute(f"CREATE TABLE IF NOT EXISTS `{db}`.`d0` USING `{db}`.`meters` (groupid, location) TAGS(0, 'Los Angles')")
|
|
||||||
assert rowsAffected == 0
|
|
||||||
|
|
||||||
except Exception as err:
|
except Exception as err:
|
||||||
print(f"Failed to create db and table, url:{url} err:{err}")
|
print(f"Failed to create db and table, url:{url} ; ErrMessage:{err}")
|
||||||
finally:
|
finally:
|
||||||
if conn:
|
if conn:
|
||||||
conn.close()
|
conn.close()
|
||||||
|
|
|
@ -9,27 +9,18 @@ try:
|
||||||
host=host,
|
host=host,
|
||||||
port=port)
|
port=port)
|
||||||
|
|
||||||
db = "power"
|
|
||||||
# create database
|
# create database
|
||||||
rowsAffected = conn.execute(f"CREATE DATABASE IF NOT EXISTS {db}")
|
rowsAffected = conn.execute(f"CREATE DATABASE IF NOT EXISTS power")
|
||||||
assert rowsAffected == 0
|
print(f"Create database power successfully, rowsAffected: {rowsAffected}");
|
||||||
|
|
||||||
# change database.
|
|
||||||
rowsAffected = conn.execute(f"USE {db}")
|
|
||||||
assert rowsAffected == 0
|
|
||||||
|
|
||||||
# create super table
|
# create super table
|
||||||
rowsAffected = conn.execute(
|
rowsAffected = conn.execute(
|
||||||
"CREATE TABLE IF NOT EXISTS `meters` (`ts` TIMESTAMP, `current` FLOAT, `voltage` INT, `phase` FLOAT) TAGS (`groupid` INT, `location` BINARY(16))"
|
"CREATE TABLE IF NOT EXISTS power.meters (`ts` TIMESTAMP, `current` FLOAT, `voltage` INT, `phase` FLOAT) TAGS (`groupid` INT, `location` BINARY(16))"
|
||||||
)
|
)
|
||||||
assert rowsAffected == 0
|
print(f"Create stable power.meters successfully, rowsAffected: {rowsAffected}");
|
||||||
|
|
||||||
# create table
|
|
||||||
rowsAffected = conn.execute("CREATE TABLE IF NOT EXISTS `d0` USING `meters` (groupid, location) TAGS(0, 'Los Angles')")
|
|
||||||
assert rowsAffected == 0
|
|
||||||
|
|
||||||
except Exception as err:
|
except Exception as err:
|
||||||
print(f"Failed to create db and table, db addrr:{host}:{port} err:{err}")
|
print(f"Failed to create db and table, db addrr:{host}:{port} ; ErrMessage:{err}")
|
||||||
finally:
|
finally:
|
||||||
if conn:
|
if conn:
|
||||||
conn.close()
|
conn.close()
|
||||||
|
|
|
@ -1,12 +1,13 @@
|
||||||
import taos
|
import taos
|
||||||
|
|
||||||
conn = None
|
conn = None
|
||||||
|
host = "localhost"
|
||||||
|
port = 6030
|
||||||
try:
|
try:
|
||||||
conn = taos.connect(user="root",
|
conn = taos.connect(host=host,
|
||||||
password="taosdata",
|
port=port,
|
||||||
host="localhost",
|
user="root",
|
||||||
port=6030)
|
password="taosdata")
|
||||||
|
|
||||||
sql = """
|
sql = """
|
||||||
INSERT INTO
|
INSERT INTO
|
||||||
|
@ -17,10 +18,10 @@ try:
|
||||||
VALUES (NOW + 1a, 10.30000, 218, 0.25000)
|
VALUES (NOW + 1a, 10.30000, 218, 0.25000)
|
||||||
"""
|
"""
|
||||||
affectedRows = conn.execute(sql)
|
affectedRows = conn.execute(sql)
|
||||||
print(f"inserted into {affectedRows} rows to power.meters successfully.")
|
print(f"Successfully inserted {affectedRows} rows to power.meters.")
|
||||||
|
|
||||||
except Exception as err:
|
except Exception as err:
|
||||||
print(err)
|
print(f"Failed to insert data to power.meters, db addr:{host}:{port} ; ErrMessage:{err}")
|
||||||
finally:
|
finally:
|
||||||
if conn:
|
if conn:
|
||||||
conn.close()
|
conn.close()
|
||||||
|
|
|
@ -1,9 +1,9 @@
|
||||||
import taosrest
|
import taosrest
|
||||||
|
|
||||||
conn = None
|
conn = None
|
||||||
|
url="http://localhost:6041"
|
||||||
try:
|
try:
|
||||||
conn = taosrest.connect(url="http://localhost:6041",
|
conn = taosrest.connect(url=url,
|
||||||
user="root",
|
user="root",
|
||||||
password="taosdata",
|
password="taosdata",
|
||||||
timeout=30)
|
timeout=30)
|
||||||
|
@ -17,10 +17,10 @@ try:
|
||||||
VALUES (NOW + 1a, 10.30000, 218, 0.25000)
|
VALUES (NOW + 1a, 10.30000, 218, 0.25000)
|
||||||
"""
|
"""
|
||||||
affectedRows = conn.execute(sql)
|
affectedRows = conn.execute(sql)
|
||||||
print(f"inserted into {affectedRows} rows to power.meters successfully.")
|
print(f"Successfully inserted {affectedRows} rows to power.meters.")
|
||||||
|
|
||||||
except Exception as err:
|
except Exception as err:
|
||||||
print(err)
|
print(f"Failed to insert data to power.meters, url:{url} ; ErrMessage:{err}")
|
||||||
finally:
|
finally:
|
||||||
if conn:
|
if conn:
|
||||||
conn.close()
|
conn.close()
|
||||||
|
|
|
@ -1,12 +1,13 @@
|
||||||
import taosws
|
import taosws
|
||||||
|
|
||||||
conn = None
|
conn = None
|
||||||
|
host="localhost"
|
||||||
|
port=6041
|
||||||
try:
|
try:
|
||||||
conn = taosws.connect(user="root",
|
conn = taosws.connect(user="root",
|
||||||
password="taosdata",
|
password="taosdata",
|
||||||
host="localhost",
|
host=host,
|
||||||
port=6041)
|
port=port)
|
||||||
|
|
||||||
sql = """
|
sql = """
|
||||||
INSERT INTO
|
INSERT INTO
|
||||||
|
@ -17,10 +18,10 @@ try:
|
||||||
VALUES (NOW + 1a, 10.30000, 218, 0.25000)
|
VALUES (NOW + 1a, 10.30000, 218, 0.25000)
|
||||||
"""
|
"""
|
||||||
affectedRows = conn.execute(sql)
|
affectedRows = conn.execute(sql)
|
||||||
print(f"inserted into {affectedRows} rows to power.meters successfully.")
|
print(f"Successfully inserted {affectedRows} rows to power.meters.")
|
||||||
|
|
||||||
except Exception as err:
|
except Exception as err:
|
||||||
print(err)
|
print(f"Failed to insert data to power.meters, db addr:{host}:{port} ; ErrMessage:{err}")
|
||||||
finally:
|
finally:
|
||||||
if conn:
|
if conn:
|
||||||
conn.close()
|
conn.close()
|
||||||
|
|
|
@ -1,26 +1,21 @@
|
||||||
import taos
|
import taos
|
||||||
|
host="localhost"
|
||||||
|
port=6030
|
||||||
conn = None
|
conn = None
|
||||||
try:
|
try:
|
||||||
conn = taos.connect(host="localhost",
|
conn = taos.connect(host=host,
|
||||||
port=6030,
|
port=port,
|
||||||
user="root",
|
user="root",
|
||||||
password="taosdata")
|
password="taosdata")
|
||||||
|
|
||||||
result = conn.query("SELECT ts, current, location FROM power.meters limit 100")
|
result = conn.query("SELECT ts, current, location FROM power.meters limit 100")
|
||||||
print(result)
|
|
||||||
# Get fields from result
|
|
||||||
fields = result.fields
|
|
||||||
for field in fields:
|
|
||||||
print(field)
|
|
||||||
|
|
||||||
# Get data from result as list of tuple
|
# Get data from result as list of tuple
|
||||||
data = result.fetch_all()
|
data = result.fetch_all()
|
||||||
for row in data:
|
for row in data:
|
||||||
print(row)
|
print(f"ts: {row[0]}, current: {row[1]}, location: {row[2]}")
|
||||||
|
|
||||||
except Exception as err:
|
except Exception as err:
|
||||||
print(f"Failed to query data from power.meters, err:{err}")
|
print(f"Failed to query data from power.meters, db addr:{host}:{port} ; ErrMessage:{err}")
|
||||||
finally:
|
finally:
|
||||||
if conn:
|
if conn:
|
||||||
conn.close()
|
conn.close()
|
|
@ -1,15 +1,17 @@
|
||||||
import taosrest
|
import taosrest
|
||||||
|
|
||||||
client = None
|
client = None
|
||||||
|
url="http://localhost:6041"
|
||||||
try:
|
try:
|
||||||
client = taosrest.RestClient(url="http://localhost:6041",
|
client = taosrest.RestClient(url=url,
|
||||||
user="root",
|
user="root",
|
||||||
password="taosdata",
|
password="taosdata",
|
||||||
timeout=30)
|
timeout=30)
|
||||||
|
|
||||||
result = client.sql(f"SELECT ts, current, location FROM power.meters limit 100", 1)
|
result = client.sql(f"SELECT ts, current, location FROM power.meters limit 100")
|
||||||
print(result)
|
if result["data"]:
|
||||||
|
for row in result["data"]:
|
||||||
|
print(f"ts: {row[0]}, current: {row[1]}, location: {row[2]}")
|
||||||
|
|
||||||
except Exception as err:
|
except Exception as err:
|
||||||
print(f"Failed to query data from power.meters, err:{err}")
|
print(f"Failed to query data from power.meters, url:{url} ; ErrMessage:{err}")
|
||||||
|
|
|
@ -1,22 +1,20 @@
|
||||||
import taosws
|
import taosws
|
||||||
|
|
||||||
conn = None
|
conn = None
|
||||||
|
host="localhost"
|
||||||
|
port=6041
|
||||||
try:
|
try:
|
||||||
conn = taosws.connect(user="root",
|
conn = taosws.connect(user="root",
|
||||||
password="taosdata",
|
password="taosdata",
|
||||||
host="localhost",
|
host=host,
|
||||||
port=6041)
|
port=port)
|
||||||
|
|
||||||
result = conn.query("SELECT ts, current, location FROM power.meters limit 100")
|
result = conn.query("SELECT ts, current, location FROM power.meters limit 100")
|
||||||
num_of_fields = result.field_count
|
|
||||||
print(num_of_fields)
|
|
||||||
|
|
||||||
for row in result:
|
for row in result:
|
||||||
print(row)
|
print(f"ts: {row[0]}, current: {row[1]}, location: {row[2]}")
|
||||||
|
|
||||||
except Exception as err:
|
except Exception as err:
|
||||||
print(f"Failed to query data from power.meters, err:{err}")
|
print(f"Failed to query data from power.meters, db addr:{host}:{port} ; ErrMessage:{err}")
|
||||||
finally:
|
finally:
|
||||||
if conn:
|
if conn:
|
||||||
conn.close()
|
conn.close()
|
||||||
|
|
|
@ -1,25 +1,24 @@
|
||||||
import taos
|
import taos
|
||||||
|
|
||||||
conn = None
|
conn = None
|
||||||
|
reqId = 3
|
||||||
|
host="localhost"
|
||||||
|
port=6030
|
||||||
try:
|
try:
|
||||||
conn = taos.connect(host="localhost",
|
conn = taos.connect(host=host,
|
||||||
port=6030,
|
port=port,
|
||||||
user="root",
|
user="root",
|
||||||
password="taosdata")
|
password="taosdata")
|
||||||
|
|
||||||
result = conn.query("SELECT ts, current, location FROM power.meters limit 100", 1)
|
result = conn.query("SELECT ts, current, location FROM power.meters limit 100", reqId)
|
||||||
# Get fields from result
|
|
||||||
fields = result.fields
|
|
||||||
for field in fields:
|
|
||||||
print(field)
|
|
||||||
|
|
||||||
# Get data from result as list of tuple
|
# Get data from result as list of tuple
|
||||||
data = result.fetch_all()
|
data = result.fetch_all()
|
||||||
for row in data:
|
for row in data:
|
||||||
print(row)
|
print(f"ts: {row[0]}, current: {row[1]}, location: {row[2]}")
|
||||||
|
|
||||||
except Exception as err:
|
except Exception as err:
|
||||||
print(f"Failed to execute sql with reqId, err:{err}")
|
print(f"Failed to execute sql with reqId:{reqId}, db addr:{host}:{port} ; ErrMessage:{err}")
|
||||||
|
|
||||||
finally:
|
finally:
|
||||||
if conn:
|
if conn:
|
||||||
conn.close()
|
conn.close()
|
||||||
|
|
|
@ -1,15 +1,18 @@
|
||||||
import taosrest
|
import taosrest
|
||||||
|
|
||||||
client = None
|
client = None
|
||||||
|
url="http://localhost:6041"
|
||||||
|
reqId = 3
|
||||||
try:
|
try:
|
||||||
client = taosrest.RestClient(url="http://localhost:6041",
|
client = taosrest.RestClient(url=url,
|
||||||
user="root",
|
user="root",
|
||||||
password="taosdata",
|
password="taosdata",
|
||||||
timeout=30)
|
timeout=30)
|
||||||
|
|
||||||
result = client.sql(f"SELECT ts, current, location FROM power.meters limit 100", 1)
|
result = client.sql(f"SELECT ts, current, location FROM power.meters limit 100", reqId)
|
||||||
print(result)
|
if result["data"]:
|
||||||
|
for row in result["data"]:
|
||||||
|
print(f"ts: {row[0]}, current: {row[1]}, location: {row[2]}")
|
||||||
|
|
||||||
except Exception as err:
|
except Exception as err:
|
||||||
print(f"Failed to execute sql with reqId, err:{err}")
|
print(f"Failed to execute sql with reqId:{reqId}, url:{url} ; ErrMessage:{err}")
|
||||||
|
|
|
@ -1,22 +1,24 @@
|
||||||
import taosws
|
import taosws
|
||||||
|
|
||||||
conn = None
|
conn = None
|
||||||
|
reqId = 3
|
||||||
|
host="localhost"
|
||||||
|
port=6041
|
||||||
try:
|
try:
|
||||||
conn = taosws.connect(
|
conn = taosws.connect(
|
||||||
user="root",
|
user="root",
|
||||||
password="taosdata",
|
password="taosdata",
|
||||||
host="localhost",
|
host=host,
|
||||||
port=6041,
|
port=port,
|
||||||
)
|
)
|
||||||
|
|
||||||
result = conn.query_with_req_id("SELECT ts, current, location FROM power.meters limit 100", req_id=1)
|
result = conn.query_with_req_id("SELECT ts, current, location FROM power.meters limit 100", req_id=3)
|
||||||
|
# Get data from result as list of tuple
|
||||||
for row in result:
|
for row in result:
|
||||||
print(row)
|
print(f"ts: {row[0]}, current: {row[1]}, location: {row[2]}")
|
||||||
|
|
||||||
except Exception as err:
|
except Exception as err:
|
||||||
print(f"Failed to execute sql with reqId, err:{err}")
|
print(f"Failed to execute sql with reqId:{reqId}, db addr:{host}:{port} ; ErrMessage:{err}")
|
||||||
finally:
|
finally:
|
||||||
if conn:
|
if conn:
|
||||||
conn.close()
|
conn.close()
|
||||||
|
|
|
@ -9,13 +9,14 @@ telnetDemo = ["metric_telnet 1707095283260 4 host=host0 interface=eth0"]
|
||||||
jsonDemo = [
|
jsonDemo = [
|
||||||
'{"metric": "metric_json","timestamp": 1626846400,"value": 10.3, "tags": {"groupid": 2, "location": "California.SanFrancisco", "id": "d1001"}}'
|
'{"metric": "metric_json","timestamp": 1626846400,"value": 10.3, "tags": {"groupid": 2, "location": "California.SanFrancisco", "id": "d1001"}}'
|
||||||
]
|
]
|
||||||
|
host = "localhost"
|
||||||
|
port = 6030
|
||||||
try:
|
try:
|
||||||
conn = taos.connect(
|
conn = taos.connect(
|
||||||
host="localhost",
|
|
||||||
user="root",
|
user="root",
|
||||||
password="taosdata",
|
password="taosdata",
|
||||||
port=6030
|
host=host,
|
||||||
|
port=port
|
||||||
)
|
)
|
||||||
|
|
||||||
conn.execute("CREATE DATABASE IF NOT EXISTS power")
|
conn.execute("CREATE DATABASE IF NOT EXISTS power")
|
||||||
|
@ -31,8 +32,9 @@ try:
|
||||||
conn.schemaless_insert(
|
conn.schemaless_insert(
|
||||||
jsonDemo, taos.SmlProtocol.JSON_PROTOCOL, taos.SmlPrecision.MILLI_SECONDS
|
jsonDemo, taos.SmlProtocol.JSON_PROTOCOL, taos.SmlPrecision.MILLI_SECONDS
|
||||||
)
|
)
|
||||||
|
print("Inserted data with schemaless successfully.");
|
||||||
except Exception as err:
|
except Exception as err:
|
||||||
print(f"Failed to insert data with schemaless, err:{err}")
|
print(f"Failed to insert data with schemaless, addr: {host}:{port} ErrMessage:{err}")
|
||||||
finally:
|
finally:
|
||||||
if conn:
|
if conn:
|
||||||
conn.close()
|
conn.close()
|
||||||
|
|
|
@ -1,6 +1,5 @@
|
||||||
import taosws
|
import taosws
|
||||||
|
|
||||||
db = "power"
|
|
||||||
def prepare():
|
def prepare():
|
||||||
conn = None
|
conn = None
|
||||||
try:
|
try:
|
||||||
|
@ -10,11 +9,12 @@ def prepare():
|
||||||
port=6041)
|
port=6041)
|
||||||
|
|
||||||
# create database
|
# create database
|
||||||
rowsAffected = conn.execute(f"CREATE DATABASE IF NOT EXISTS {db}")
|
rowsAffected = conn.execute(f"CREATE DATABASE IF NOT EXISTS power")
|
||||||
assert rowsAffected == 0
|
assert rowsAffected == 0
|
||||||
|
|
||||||
except Exception as err:
|
except Exception as err:
|
||||||
print(f"Failed to create db and table, err:{err}")
|
print(f"Failed to create db and table, err:{err}")
|
||||||
|
raise err
|
||||||
finally:
|
finally:
|
||||||
if conn:
|
if conn:
|
||||||
conn.close()
|
conn.close()
|
||||||
|
@ -32,13 +32,14 @@ def schemaless_insert():
|
||||||
jsonDemo = [
|
jsonDemo = [
|
||||||
'{"metric": "metric_json","timestamp": 1626846400,"value": 10.3, "tags": {"groupid": 2, "location": "California.SanFrancisco", "id": "d1001"}}'
|
'{"metric": "metric_json","timestamp": 1626846400,"value": 10.3, "tags": {"groupid": 2, "location": "California.SanFrancisco", "id": "d1001"}}'
|
||||||
]
|
]
|
||||||
|
host = "localhost"
|
||||||
|
port = 6041
|
||||||
try:
|
try:
|
||||||
conn = taosws.connect(user="root",
|
conn = taosws.connect(user="root",
|
||||||
password="taosdata",
|
password="taosdata",
|
||||||
host="localhost",
|
host=host,
|
||||||
port=6041,
|
port=port,
|
||||||
database=db)
|
database='power')
|
||||||
|
|
||||||
conn.schemaless_insert(
|
conn.schemaless_insert(
|
||||||
lines = lineDemo,
|
lines = lineDemo,
|
||||||
|
@ -63,10 +64,18 @@ def schemaless_insert():
|
||||||
ttl=1,
|
ttl=1,
|
||||||
req_id=3,
|
req_id=3,
|
||||||
)
|
)
|
||||||
|
print("Inserted data with schemaless successfully.");
|
||||||
except Exception as err:
|
except Exception as err:
|
||||||
print(f"Failed to insert data with schemaless, err:{err}")
|
print(f"Failed to insert data with schemaless, addr: {host}:{port} ErrMessage:{err}")
|
||||||
|
raise err
|
||||||
|
|
||||||
finally:
|
finally:
|
||||||
if conn:
|
if conn:
|
||||||
conn.close()
|
conn.close()
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
try:
|
||||||
|
prepare()
|
||||||
|
schemaless_insert
|
||||||
|
except Exception as err:
|
||||||
|
print(f"Failed to insert data with schemaless, err:{err}")
|
|
@ -7,13 +7,14 @@ numOfRow = 10
|
||||||
|
|
||||||
conn = None
|
conn = None
|
||||||
stmt = None
|
stmt = None
|
||||||
|
host="localhost",
|
||||||
|
port=6030,
|
||||||
try:
|
try:
|
||||||
conn = taos.connect(
|
conn = taos.connect(
|
||||||
host="localhost",
|
|
||||||
user="root",
|
user="root",
|
||||||
password="taosdata",
|
password="taosdata",
|
||||||
port=6030,
|
host=host,
|
||||||
|
port=port,
|
||||||
)
|
)
|
||||||
|
|
||||||
conn.execute("CREATE DATABASE IF NOT EXISTS power")
|
conn.execute("CREATE DATABASE IF NOT EXISTS power")
|
||||||
|
@ -52,10 +53,10 @@ try:
|
||||||
params[3].float(phases)
|
params[3].float(phases)
|
||||||
stmt.bind_param_batch(params)
|
stmt.bind_param_batch(params)
|
||||||
stmt.execute()
|
stmt.execute()
|
||||||
print(f"stmt insert successfully.")
|
print(f"Successfully inserted to power.meters.")
|
||||||
|
|
||||||
except Exception as err:
|
except Exception as err:
|
||||||
print(f"Failed to insert to table meters using stmt, error: {err}")
|
print(f"Failed to insert to table meters using stmt, addr:{host}:{port} ; ErrMessage:{err}")
|
||||||
finally:
|
finally:
|
||||||
if stmt:
|
if stmt:
|
||||||
stmt.close()
|
stmt.close()
|
||||||
|
|
|
@ -8,6 +8,8 @@ numOfRow = 10
|
||||||
|
|
||||||
conn = None
|
conn = None
|
||||||
stmt = None
|
stmt = None
|
||||||
|
host="localhost"
|
||||||
|
port=6041
|
||||||
try:
|
try:
|
||||||
conn = taosws.connect(user="root",
|
conn = taosws.connect(user="root",
|
||||||
password="taosdata",
|
password="taosdata",
|
||||||
|
@ -56,10 +58,10 @@ try:
|
||||||
stmt.add_batch()
|
stmt.add_batch()
|
||||||
stmt.execute()
|
stmt.execute()
|
||||||
|
|
||||||
print(f"stmt insert successfully.")
|
print(f"Successfully inserted to power.meters.")
|
||||||
|
|
||||||
except Exception as err:
|
except Exception as err:
|
||||||
print(f"Failed to insert to table meters using stmt, error: {err}")
|
print(f"Failed to insert to table meters using stmt, addr:{host}:{port} ; ErrMessage:{err}")
|
||||||
finally:
|
finally:
|
||||||
if stmt:
|
if stmt:
|
||||||
stmt.close()
|
stmt.close()
|
||||||
|
|
|
@ -37,9 +37,9 @@ def prepareMeta():
|
||||||
VALUES (NOW + 1a, 10.30000, 218, 0.25000)
|
VALUES (NOW + 1a, 10.30000, 218, 0.25000)
|
||||||
"""
|
"""
|
||||||
affectedRows = conn.execute(sql)
|
affectedRows = conn.execute(sql)
|
||||||
print(f"inserted into {affectedRows} rows to power.meters successfully.")
|
print(f"Inserted into {affectedRows} rows to power.meters successfully.")
|
||||||
except Exception as err:
|
except Exception as err:
|
||||||
print(f"prepare meta err:{err}")
|
print(f"Prepare insert data error, ErrMessage:{err}")
|
||||||
raise err
|
raise err
|
||||||
finally:
|
finally:
|
||||||
if conn:
|
if conn:
|
||||||
|
@ -49,23 +49,28 @@ def prepareMeta():
|
||||||
from taos.tmq import Consumer
|
from taos.tmq import Consumer
|
||||||
|
|
||||||
def create_consumer():
|
def create_consumer():
|
||||||
|
host = "localhost"
|
||||||
|
port = 6030
|
||||||
|
groupId = "group1"
|
||||||
|
clientId = "1"
|
||||||
try:
|
try:
|
||||||
consumer = Consumer(
|
consumer = Consumer(
|
||||||
{
|
{
|
||||||
"group.id": "group1",
|
"group.id": groupId,
|
||||||
"client.id": "1",
|
"client.id": clientId,
|
||||||
"td.connect.user": "root",
|
"td.connect.user": "root",
|
||||||
"td.connect.pass": "taosdata",
|
"td.connect.pass": "taosdata",
|
||||||
"enable.auto.commit": "true",
|
"enable.auto.commit": "true",
|
||||||
"auto.commit.interval.ms": "1000",
|
"auto.commit.interval.ms": "1000",
|
||||||
"auto.offset.reset": "latest",
|
"auto.offset.reset": "latest",
|
||||||
"td.connect.ip": "localhost",
|
"td.connect.ip": host,
|
||||||
"td.connect.port": "6030",
|
"td.connect.port": port,
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
print(f"Create consumer successfully, host: {host}:{port}, groupId: {groupId}, clientId: {clientId}");
|
||||||
return consumer
|
return consumer
|
||||||
except Exception as err:
|
except Exception as err:
|
||||||
print(f"Failed to poll data, err:{err}")
|
print(f"Failed to create native consumer, host: {host}:{port} ; ErrMessage:{err}");
|
||||||
raise err
|
raise err
|
||||||
# ANCHOR_END: create_consumer
|
# ANCHOR_END: create_consumer
|
||||||
|
|
||||||
|
@ -75,22 +80,23 @@ def subscribe(consumer):
|
||||||
try:
|
try:
|
||||||
# subscribe to the topics
|
# subscribe to the topics
|
||||||
consumer.subscribe(["topic_meters"])
|
consumer.subscribe(["topic_meters"])
|
||||||
print("subscribe topics successfully")
|
print("Subscribe topics successfully")
|
||||||
for i in range(50):
|
for i in range(50):
|
||||||
records = consumer.poll(1)
|
records = consumer.poll(1)
|
||||||
if records:
|
if records:
|
||||||
err = records.error()
|
err = records.error()
|
||||||
if err is not None:
|
if err is not None:
|
||||||
print(f"poll data error, {err}")
|
print(f"Poll data error, {err}")
|
||||||
raise err
|
raise err
|
||||||
|
|
||||||
val = records.value()
|
val = records.value()
|
||||||
if val:
|
if val:
|
||||||
for block in val:
|
for block in val:
|
||||||
print(block.fetchall())
|
data = block.fetchall()
|
||||||
|
print(f"data: {data}")
|
||||||
|
|
||||||
except Exception as err:
|
except Exception as err:
|
||||||
print(f"Failed to poll data, err:{err}")
|
print(f"Failed to poll data, ErrMessage:{err}")
|
||||||
raise err
|
raise err
|
||||||
|
|
||||||
|
|
||||||
|
@ -104,7 +110,7 @@ def commit_offset(consumer):
|
||||||
if records:
|
if records:
|
||||||
err = records.error()
|
err = records.error()
|
||||||
if err is not None:
|
if err is not None:
|
||||||
print(f"poll data error, {err}")
|
print(f"Poll data error, {err}")
|
||||||
raise err
|
raise err
|
||||||
|
|
||||||
val = records.value()
|
val = records.value()
|
||||||
|
@ -114,9 +120,10 @@ def commit_offset(consumer):
|
||||||
|
|
||||||
# after processing the data, commit the offset manually
|
# after processing the data, commit the offset manually
|
||||||
consumer.commit(records)
|
consumer.commit(records)
|
||||||
|
print("Commit offset manually successfully.");
|
||||||
|
|
||||||
except Exception as err:
|
except Exception as err:
|
||||||
print(f"Failed to poll data, err:{err}")
|
print(f"Failed to poll data, ErrMessage:{err}")
|
||||||
raise err
|
raise err
|
||||||
# ANCHOR_END: commit_offset
|
# ANCHOR_END: commit_offset
|
||||||
|
|
||||||
|
@ -127,25 +134,25 @@ def seek_offset(consumer):
|
||||||
assignments = consumer.assignment()
|
assignments = consumer.assignment()
|
||||||
if assignments:
|
if assignments:
|
||||||
for partition in assignments:
|
for partition in assignments:
|
||||||
print(f"first data polled: {partition.offset}")
|
|
||||||
partition.offset = 0
|
partition.offset = 0
|
||||||
consumer.seek(partition)
|
consumer.seek(partition)
|
||||||
print(f"assignment seek to beginning successfully");
|
print(f"Assignment seek to beginning successfully");
|
||||||
except Exception as err:
|
except Exception as err:
|
||||||
print(f"seek example failed; err:{err}")
|
print(f"Seek example failed; ErrMessage:{err}")
|
||||||
raise err
|
raise err
|
||||||
# ANCHOR_END: assignment
|
# ANCHOR_END: assignment
|
||||||
|
|
||||||
|
|
||||||
# ANCHOR: unsubscribe
|
|
||||||
def unsubscribe(consumer):
|
def unsubscribe(consumer):
|
||||||
|
# ANCHOR: unsubscribe
|
||||||
try:
|
try:
|
||||||
consumer.unsubscribe()
|
consumer.unsubscribe()
|
||||||
|
print("Consumer unsubscribed successfully.");
|
||||||
except Exception as err:
|
except Exception as err:
|
||||||
print(f"Failed to unsubscribe consumer. err:{err}")
|
print(f"Failed to unsubscribe consumer. ErrMessage:{err}")
|
||||||
|
finally:
|
||||||
|
if consumer:
|
||||||
# ANCHOR_END: unsubscribe
|
consumer.close()
|
||||||
|
# ANCHOR_END: unsubscribe
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
consumer = None
|
consumer = None
|
||||||
|
@ -155,9 +162,10 @@ if __name__ == "__main__":
|
||||||
subscribe(consumer)
|
subscribe(consumer)
|
||||||
seek_offset(consumer)
|
seek_offset(consumer)
|
||||||
commit_offset(consumer)
|
commit_offset(consumer)
|
||||||
unsubscribe(consumer)
|
consumer.unsubscribe()
|
||||||
|
print("Consumer unsubscribed successfully.");
|
||||||
except Exception as err:
|
except Exception as err:
|
||||||
print(f"Failed to stmt consumer. err:{err}")
|
print(f"Failed to stmt consumer. ErrMessage:{err}")
|
||||||
finally:
|
finally:
|
||||||
if consumer:
|
consumer.unsubscribe()
|
||||||
consumer.close()
|
|
||||||
|
|
|
@ -48,10 +48,10 @@ def prepareMeta():
|
||||||
VALUES (NOW + 1a, 10.30000, 218, 0.25000)
|
VALUES (NOW + 1a, 10.30000, 218, 0.25000)
|
||||||
"""
|
"""
|
||||||
affectedRows = conn.execute(sql)
|
affectedRows = conn.execute(sql)
|
||||||
print(f"inserted into {affectedRows} rows to power.meters successfully.")
|
print(f"Inserted into {affectedRows} rows to power.meters successfully.")
|
||||||
|
|
||||||
except Exception as err:
|
except Exception as err:
|
||||||
print(f"Failed to prepareMeta {err}")
|
print(f"Failed to prepareMeta ErrMessage:{err}")
|
||||||
raise err
|
raise err
|
||||||
finally:
|
finally:
|
||||||
if conn:
|
if conn:
|
||||||
|
@ -60,20 +60,25 @@ def prepareMeta():
|
||||||
|
|
||||||
# ANCHOR: create_consumer
|
# ANCHOR: create_consumer
|
||||||
def create_consumer():
|
def create_consumer():
|
||||||
|
host = "localhost"
|
||||||
|
port = 6041
|
||||||
|
groupId = "group1"
|
||||||
|
clientId = "1"
|
||||||
try:
|
try:
|
||||||
consumer = taosws.Consumer(conf={
|
consumer = taosws.Consumer(conf={
|
||||||
"td.connect.websocket.scheme": "ws",
|
"td.connect.websocket.scheme": "ws",
|
||||||
"group.id": "group1",
|
"group.id": groupId,
|
||||||
"client.id": "1",
|
"client.id": clientId,
|
||||||
"auto.offset.reset": "latest",
|
"auto.offset.reset": "latest",
|
||||||
"td.connect.ip": "localhost",
|
"td.connect.ip": host,
|
||||||
"td.connect.port": "6041",
|
"td.connect.port": port,
|
||||||
"enable.auto.commit": "true",
|
"enable.auto.commit": "true",
|
||||||
"auto.commit.interval.ms": "1000",
|
"auto.commit.interval.ms": "1000",
|
||||||
})
|
})
|
||||||
|
print(f"Create consumer successfully, host: {host}:{port}, groupId: {groupId}, clientId: {clientId}");
|
||||||
return consumer;
|
return consumer;
|
||||||
except Exception as err:
|
except Exception as err:
|
||||||
print(f"Failed to create websocket consumer, err:{err}");
|
print(f"Failed to create websocket consumer, host: {host}:{port} ; ErrMessage:{err}");
|
||||||
raise err
|
raise err
|
||||||
|
|
||||||
|
|
||||||
|
@ -90,10 +95,10 @@ def seek_offset(consumer):
|
||||||
print(
|
print(
|
||||||
f"vg_id: {assign.vg_id()}, offset: {assign.offset()}, begin: {assign.begin()}, end: {assign.end()}")
|
f"vg_id: {assign.vg_id()}, offset: {assign.offset()}, begin: {assign.begin()}, end: {assign.end()}")
|
||||||
consumer.seek(topic, assign.vg_id(), assign.begin())
|
consumer.seek(topic, assign.vg_id(), assign.begin())
|
||||||
print("assignment seek to beginning successfully");
|
print("Assignment seek to beginning successfully");
|
||||||
|
|
||||||
except Exception as err:
|
except Exception as err:
|
||||||
print(f"seek example failed; err:{err}")
|
print(f"Seek example failed; ErrMessage:{err}")
|
||||||
raise err
|
raise err
|
||||||
# ANCHOR_END: assignment
|
# ANCHOR_END: assignment
|
||||||
|
|
||||||
|
@ -102,16 +107,16 @@ def seek_offset(consumer):
|
||||||
def subscribe(consumer):
|
def subscribe(consumer):
|
||||||
try:
|
try:
|
||||||
consumer.subscribe([topic])
|
consumer.subscribe([topic])
|
||||||
print("subscribe topics successfully")
|
print("Subscribe topics successfully")
|
||||||
for i in range(50):
|
for i in range(50):
|
||||||
records = consumer.poll(timeout=1.0)
|
records = consumer.poll(timeout=1.0)
|
||||||
if records:
|
if records:
|
||||||
for block in records:
|
for block in records:
|
||||||
for row in block:
|
for row in block:
|
||||||
print(row)
|
print(f"data: {row}")
|
||||||
|
|
||||||
except Exception as err:
|
except Exception as err:
|
||||||
print(f"Failed to poll data, err:{err}")
|
print(f"Failed to poll data, ErrMessage:{err}")
|
||||||
raise err
|
raise err
|
||||||
|
|
||||||
|
|
||||||
|
@ -125,25 +130,30 @@ def commit_offset(consumer):
|
||||||
if records:
|
if records:
|
||||||
for block in records:
|
for block in records:
|
||||||
for row in block:
|
for row in block:
|
||||||
print(row)
|
print(f"data: {row}")
|
||||||
|
|
||||||
# after processing the data, commit the offset manually
|
# after processing the data, commit the offset manually
|
||||||
consumer.commit(records)
|
consumer.commit(records)
|
||||||
|
print("Commit offset manually successfully.");
|
||||||
|
|
||||||
except Exception as err:
|
except Exception as err:
|
||||||
print(f"Failed to poll data, err:{err}")
|
print(f"Failed to poll data, ErrMessage:{err}")
|
||||||
raise err
|
raise err
|
||||||
|
|
||||||
|
|
||||||
# ANCHOR_END: commit_offset
|
# ANCHOR_END: commit_offset
|
||||||
#
|
#
|
||||||
# ANCHOR: unsubscribe
|
|
||||||
def unsubscribe(consumer):
|
def unsubscribe(consumer):
|
||||||
|
# ANCHOR: unsubscribe
|
||||||
try:
|
try:
|
||||||
consumer.unsubscribe()
|
consumer.unsubscribe()
|
||||||
|
print("Consumer unsubscribed successfully.");
|
||||||
except Exception as err:
|
except Exception as err:
|
||||||
print("Failed to unsubscribe consumer. err:{err}")
|
print(f"Failed to unsubscribe consumer. ErrMessage:{err}")
|
||||||
|
finally:
|
||||||
|
if consumer:
|
||||||
|
consumer.close()
|
||||||
|
|
||||||
# ANCHOR_END: unsubscribe
|
# ANCHOR_END: unsubscribe
|
||||||
|
|
||||||
|
@ -154,10 +164,8 @@ if __name__ == "__main__":
|
||||||
consumer = create_consumer()
|
consumer = create_consumer()
|
||||||
subscribe(consumer)
|
subscribe(consumer)
|
||||||
seek_offset(consumer)
|
seek_offset(consumer)
|
||||||
commit_offset(consumer)
|
commit_offset(consumer)
|
||||||
unsubscribe(consumer)
|
|
||||||
except Exception as err:
|
except Exception as err:
|
||||||
print(f"Failed to stmt consumer. err:{err}")
|
print(f"Failed to stmt consumer. ErrorMessage:{err}")
|
||||||
finally:
|
finally:
|
||||||
if consumer:
|
unsubscribe(consumer);
|
||||||
consumer.close()
|
|
|
@ -1,9 +1,17 @@
|
||||||
use taos::*;
|
use taos::*;
|
||||||
|
|
||||||
#[tokio::main]
|
#[tokio::main]
|
||||||
async fn main() -> Result<(), Error> {
|
async fn main() -> anyhow::Result<()> {
|
||||||
#[allow(unused_variables)]
|
let dsn = "taos://localhost:6030".to_string();
|
||||||
let taos = TaosBuilder::from_dsn("taos://localhost:6030")?.build()?;
|
|
||||||
println!("Connected to localhost with native connection successfully.");
|
match TaosBuilder::from_dsn(&dsn)?.build().await {
|
||||||
Ok(())
|
Ok(_taos) => {
|
||||||
|
println!("Connected to {} successfully.", dsn);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
Err(err) => {
|
||||||
|
eprintln!("Failed to connect to {}; ErrMessage: {}", dsn, err);
|
||||||
|
return Err(err.into());
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -0,0 +1,35 @@
|
||||||
|
use taos::*;
|
||||||
|
|
||||||
|
#[tokio::main]
|
||||||
|
async fn main() -> anyhow::Result<()> {
|
||||||
|
let url = "taos://localhost:6030";
|
||||||
|
|
||||||
|
// ANCHOR: create_db_and_table
|
||||||
|
let taos = TaosBuilder::from_dsn(url)?.build().await?;
|
||||||
|
|
||||||
|
// create database and use it
|
||||||
|
match taos.exec_many([
|
||||||
|
"CREATE DATABASE IF NOT EXISTS power",
|
||||||
|
]).await {
|
||||||
|
Ok(afffected_rows) => println!("Create database power successfully, rowsAffected: {}", afffected_rows),
|
||||||
|
Err(err) => {
|
||||||
|
eprintln!("Failed to create database power; ErrMessage: {}", err);
|
||||||
|
return Err(err.into());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// create super table
|
||||||
|
match taos.exec_many([
|
||||||
|
"CREATE STABLE IF NOT EXISTS power.meters (`ts` TIMESTAMP, `current` FLOAT, `voltage` INT, `phase` FLOAT) \
|
||||||
|
TAGS (`groupid` INT, `location` BINARY(24))",
|
||||||
|
]).await {
|
||||||
|
Ok(afffected_rows) => println!("Create stable power.meters successfully, rowsAffected: {}", afffected_rows),
|
||||||
|
Err(err) => {
|
||||||
|
eprintln!("Failed to create stable power.meters; ErrMessage: {}", err);
|
||||||
|
return Err(err.into());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
// ANCHOR_END: create_db_and_table
|
||||||
|
}
|
|
@ -0,0 +1,31 @@
|
||||||
|
use taos::*;
|
||||||
|
|
||||||
|
#[tokio::main]
|
||||||
|
async fn main() -> anyhow::Result<()> {
|
||||||
|
let dsn = "taos://localhost:6030";
|
||||||
|
let builder = TaosBuilder::from_dsn(dsn)?;
|
||||||
|
|
||||||
|
let taos = builder.build().await?;
|
||||||
|
|
||||||
|
|
||||||
|
// ANCHOR: insert_data
|
||||||
|
match taos.exec(r#"INSERT INTO
|
||||||
|
power.d1001 USING power.meters 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 TAGS(3, 'California.SanFrancisco')
|
||||||
|
VALUES
|
||||||
|
(NOW + 1a, 10.30000, 218, 0.25000) "#).await{
|
||||||
|
Ok(affected_rows) => println!("Successfully inserted {} rows to power.meters.", affected_rows),
|
||||||
|
Err(err) => {
|
||||||
|
eprintln!("Failed to insert data to power.meters, dsn: {}; ErrMessage: {}", dsn, err);
|
||||||
|
return Err(err.into());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ANCHOR_END: insert_data
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
|
@ -9,58 +9,33 @@ async fn main() -> anyhow::Result<()> {
|
||||||
|
|
||||||
let taos = builder.build().await?;
|
let taos = builder.build().await?;
|
||||||
|
|
||||||
// ANCHOR: create_db_and_table
|
|
||||||
let db = "power";
|
|
||||||
// create database
|
|
||||||
taos.exec_many([
|
|
||||||
format!("CREATE DATABASE IF NOT EXISTS `{db}`"),
|
|
||||||
format!("USE `{db}`"),
|
|
||||||
])
|
|
||||||
.await?;
|
|
||||||
println!("Create database power successfully.");
|
|
||||||
|
|
||||||
// create super table
|
|
||||||
taos.exec_many([
|
|
||||||
"CREATE STABLE IF NOT EXISTS `meters` (`ts` TIMESTAMP, `current` FLOAT, `voltage` INT, `phase` FLOAT) \
|
|
||||||
TAGS (`groupid` INT, `location` BINARY(24))",
|
|
||||||
]).await?;
|
|
||||||
println!("Create stable meters successfully.");
|
|
||||||
|
|
||||||
// ANCHOR_END: create_db_and_table
|
|
||||||
|
|
||||||
// ANCHOR: insert_data
|
|
||||||
let inserted = taos.exec(r#"INSERT INTO
|
|
||||||
power.d1001 USING power.meters 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 TAGS(3, 'California.SanFrancisco')
|
|
||||||
VALUES
|
|
||||||
(NOW + 1a, 10.30000, 218, 0.25000) "#).await?;
|
|
||||||
|
|
||||||
println!("inserted: {} rows to power.meters successfully.", inserted);
|
|
||||||
// ANCHOR_END: insert_data
|
|
||||||
|
|
||||||
// ANCHOR: query_data
|
// ANCHOR: query_data
|
||||||
// query data, make sure the database and table are created before
|
// query data, make sure the database and table are created before
|
||||||
let mut result = taos.query("SELECT ts, current, location FROM power.meters limit 100").await?;
|
match taos.query("SELECT ts, current, location FROM power.meters limit 100").await{
|
||||||
|
Ok(mut result) => {
|
||||||
for field in result.fields() {
|
for field in result.fields() {
|
||||||
println!("got field: {}", field.name());
|
println!("got field: {}", field.name());
|
||||||
}
|
}
|
||||||
|
|
||||||
let mut rows = result.rows();
|
let mut rows = result.rows();
|
||||||
let mut nrows = 0;
|
let mut nrows = 0;
|
||||||
while let Some(row) = rows.try_next().await? {
|
while let Some(row) = rows.try_next().await? {
|
||||||
for (col, (name, value)) in row.enumerate() {
|
for (col, (name, value)) in row.enumerate() {
|
||||||
println!(
|
println!(
|
||||||
"[{}] got value in col {} (named `{:>8}`): {}",
|
"[{}] got value in col {} (named `{:>8}`): {}",
|
||||||
nrows, col, name, value
|
nrows, col, name, value
|
||||||
);
|
);
|
||||||
|
}
|
||||||
|
nrows += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(err) => {
|
||||||
|
eprintln!("Failed to query data from power.meters, dsn: {}; ErrMessage: {}", dsn, err);
|
||||||
|
return Err(err.into());
|
||||||
}
|
}
|
||||||
nrows += 1;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
// ANCHOR_END: query_data
|
// ANCHOR_END: query_data
|
||||||
|
|
||||||
// ANCHOR: query_data_2
|
// ANCHOR: query_data_2
|
||||||
|
@ -72,30 +47,56 @@ async fn main() -> anyhow::Result<()> {
|
||||||
ts: DateTime<Local>,
|
ts: DateTime<Local>,
|
||||||
// float to f32
|
// float to f32
|
||||||
current: Option<f32>,
|
current: Option<f32>,
|
||||||
// int to i32
|
|
||||||
voltage: Option<i32>,
|
|
||||||
phase: Option<f32>,
|
|
||||||
groupid: i32,
|
|
||||||
// binary/varchar to String
|
// binary/varchar to String
|
||||||
location: String,
|
location: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
let records: Vec<Record> = taos
|
match taos.query("SELECT ts, current, location FROM power.meters limit 100").await {
|
||||||
.query("select ts, current, voltage, phase, groupid, location from power.meters limit 100")
|
Ok(mut query) => {
|
||||||
.await?
|
match query.deserialize::<Record>().try_collect::<Vec<_>>().await {
|
||||||
.deserialize()
|
Ok(records) => {
|
||||||
.try_collect()
|
dbg!(records);
|
||||||
.await?;
|
}
|
||||||
|
Err(err) => {
|
||||||
dbg!(records);
|
eprintln!("Failed to deserialize query results; ErrMessage: {}", err);
|
||||||
|
return Err(err.into());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(err) => {
|
||||||
|
eprintln!("Failed to query data from power.meters, url: {}; ErrMessage: {}", dsn, err);
|
||||||
|
return Err(err.into());
|
||||||
|
}
|
||||||
|
}
|
||||||
// ANCHOR_END: query_data_2
|
// ANCHOR_END: query_data_2
|
||||||
|
|
||||||
// ANCHOR: query_with_req_id
|
// ANCHOR: query_with_req_id
|
||||||
let result = taos.query_with_req_id("SELECT ts, current, location FROM power.meters limit 1", 1).await?;
|
|
||||||
for field in result.fields() {
|
let req_id :u64 = 3;
|
||||||
println!("got field: {}", field.name());
|
match taos.query_with_req_id("SELECT ts, current, location FROM power.meters limit 1", req_id).await{
|
||||||
|
Ok(mut result) => {
|
||||||
|
for field in result.fields() {
|
||||||
|
println!("got field: {}", field.name());
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut rows = result.rows();
|
||||||
|
let mut nrows = 0;
|
||||||
|
while let Some(row) = rows.try_next().await? {
|
||||||
|
for (col, (name, value)) in row.enumerate() {
|
||||||
|
println!(
|
||||||
|
"[{}] got value in col {} (named `{:>8}`): {}",
|
||||||
|
nrows, col, name, value
|
||||||
|
);
|
||||||
|
}
|
||||||
|
nrows += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(err) => {
|
||||||
|
eprintln!("Failed to execute sql with reqId: {}, dsn: {}; ErrMessage: {}", req_id, dsn, err);
|
||||||
|
return Err(err.into());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
println!("query with reqId successfully");
|
|
||||||
// ANCHOR_END: query_with_req_id
|
// ANCHOR_END: query_with_req_id
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
|
@ -11,7 +11,8 @@ use taos::taos_query;
|
||||||
async fn main() -> anyhow::Result<()> {
|
async fn main() -> anyhow::Result<()> {
|
||||||
std::env::set_var("RUST_LOG", "taos=debug");
|
std::env::set_var("RUST_LOG", "taos=debug");
|
||||||
pretty_env_logger::init();
|
pretty_env_logger::init();
|
||||||
let dsn = "taos://localhost:6030".to_string();
|
let host = "localhost";
|
||||||
|
let dsn = format!("taos://{}:6030", host);
|
||||||
log::debug!("dsn: {:?}", &dsn);
|
log::debug!("dsn: {:?}", &dsn);
|
||||||
|
|
||||||
let client = TaosBuilder::from_dsn(dsn)?.build().await?;
|
let client = TaosBuilder::from_dsn(dsn)?.build().await?;
|
||||||
|
@ -39,7 +40,13 @@ async fn main() -> anyhow::Result<()> {
|
||||||
.ttl(1000)
|
.ttl(1000)
|
||||||
.req_id(100u64)
|
.req_id(100u64)
|
||||||
.build()?;
|
.build()?;
|
||||||
assert_eq!(client.put(&sml_data).await?, ());
|
match client.put(&sml_data).await{
|
||||||
|
Ok(_) => {},
|
||||||
|
Err(err) => {
|
||||||
|
eprintln!("Failed to insert data with schemaless, host: {}; ErrMessage: {}", host, err);
|
||||||
|
return Err(err.into());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// SchemalessProtocol::Telnet
|
// SchemalessProtocol::Telnet
|
||||||
let data = [
|
let data = [
|
||||||
|
@ -55,7 +62,13 @@ async fn main() -> anyhow::Result<()> {
|
||||||
.ttl(1000)
|
.ttl(1000)
|
||||||
.req_id(200u64)
|
.req_id(200u64)
|
||||||
.build()?;
|
.build()?;
|
||||||
assert_eq!(client.put(&sml_data).await?, ());
|
match client.put(&sml_data).await{
|
||||||
|
Ok(_) => {},
|
||||||
|
Err(err) => {
|
||||||
|
eprintln!("Failed to insert data with schemaless, host: {}; ErrMessage: {}", host, err);
|
||||||
|
return Err(err.into());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// SchemalessProtocol::Json
|
// SchemalessProtocol::Json
|
||||||
let data = [
|
let data = [
|
||||||
|
@ -80,7 +93,13 @@ async fn main() -> anyhow::Result<()> {
|
||||||
.ttl(1000)
|
.ttl(1000)
|
||||||
.req_id(300u64)
|
.req_id(300u64)
|
||||||
.build()?;
|
.build()?;
|
||||||
assert_eq!(client.put(&sml_data).await?, ());
|
match client.put(&sml_data).await{
|
||||||
|
Ok(_) => {},
|
||||||
|
Err(err) => {
|
||||||
|
eprintln!("Failed to insert data with schemaless, host: {}; ErrMessage: {}", host, err);
|
||||||
|
return Err(err.into());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
println!("Inserted data with schemaless successfully.");
|
println!("Inserted data with schemaless successfully.");
|
||||||
Ok(())
|
Ok(())
|
||||||
|
|
|
@ -2,12 +2,13 @@ use taos::*;
|
||||||
|
|
||||||
#[tokio::main]
|
#[tokio::main]
|
||||||
async fn main() -> anyhow::Result<()> {
|
async fn main() -> anyhow::Result<()> {
|
||||||
let taos = TaosBuilder::from_dsn("taos://")?.build().await?;
|
let dsn = "taos://localhost:6030";
|
||||||
|
let taos = TaosBuilder::from_dsn(dsn)?.build().await?;
|
||||||
|
|
||||||
taos.exec("DROP DATABASE IF EXISTS power").await?;
|
taos.exec("DROP DATABASE IF EXISTS power").await?;
|
||||||
taos.create_database("power").await?;
|
taos.create_database("power").await?;
|
||||||
taos.use_database("power").await?;
|
taos.use_database("power").await?;
|
||||||
taos.exec("CREATE STABLE IF NOT EXISTS meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (location BINARY(64), groupId INT)").await?;
|
taos.exec("CREATE STABLE IF NOT EXISTS power.meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (groupId INT, location BINARY(24))").await?;
|
||||||
|
|
||||||
let mut stmt = Stmt::init(&taos).await?;
|
let mut stmt = Stmt::init(&taos).await?;
|
||||||
stmt.prepare("INSERT INTO ? USING meters TAGS(?, ?) VALUES(?, ?, ?, ?)").await?;
|
stmt.prepare("INSERT INTO ? USING meters TAGS(?, ?) VALUES(?, ?, ?, ?)").await?;
|
||||||
|
@ -15,8 +16,8 @@ async fn main() -> anyhow::Result<()> {
|
||||||
const NUM_TABLES: usize = 10;
|
const NUM_TABLES: usize = 10;
|
||||||
const NUM_ROWS: usize = 10;
|
const NUM_ROWS: usize = 10;
|
||||||
for i in 0..NUM_TABLES {
|
for i in 0..NUM_TABLES {
|
||||||
let table_name = format!("d{}", i);
|
let table_name = format!("d_bind_{}", i);
|
||||||
let tags = vec![Value::VarChar("California.SanFransico".into()), Value::Int(2)];
|
let tags = vec![Value::Int(i as i32), Value::VarChar(format!("location_{}", i).into())];
|
||||||
|
|
||||||
// set table name and tags for the prepared statement.
|
// set table name and tags for the prepared statement.
|
||||||
stmt.set_tbname_tags(&table_name, &tags).await?;
|
stmt.set_tbname_tags(&table_name, &tags).await?;
|
||||||
|
@ -35,9 +36,13 @@ async fn main() -> anyhow::Result<()> {
|
||||||
}
|
}
|
||||||
|
|
||||||
// execute.
|
// execute.
|
||||||
let rows = stmt.execute().await?;
|
match stmt.execute().await{
|
||||||
assert_eq!(rows, NUM_TABLES * NUM_ROWS);
|
Ok(affected_rows) => println!("Successfully inserted {} rows to power.meters.", affected_rows),
|
||||||
|
Err(err) => {
|
||||||
|
eprintln!("Failed to insert to table meters using stmt, dsn: {}; ErrMessage: {}", dsn, err);
|
||||||
|
return Err(err.into());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
println!("execute stmt insert successfully");
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
|
@ -12,7 +12,7 @@ async fn main() -> anyhow::Result<()> {
|
||||||
use taos_query::prelude::*;
|
use taos_query::prelude::*;
|
||||||
// ANCHOR: create_consumer_dsn
|
// ANCHOR: create_consumer_dsn
|
||||||
let dsn = "taos://localhost:6030".to_string();
|
let dsn = "taos://localhost:6030".to_string();
|
||||||
log::info!("dsn: {}", dsn);
|
println!("dsn: {}", dsn);
|
||||||
let mut dsn = Dsn::from_str(&dsn)?;
|
let mut dsn = Dsn::from_str(&dsn)?;
|
||||||
// ANCHOR_END: create_consumer_dsn
|
// ANCHOR_END: create_consumer_dsn
|
||||||
|
|
||||||
|
@ -37,20 +37,36 @@ async fn main() -> anyhow::Result<()> {
|
||||||
// ANCHOR_END: create_topic
|
// ANCHOR_END: create_topic
|
||||||
|
|
||||||
// ANCHOR: create_consumer_ac
|
// ANCHOR: create_consumer_ac
|
||||||
|
let group_id = "group1".to_string();
|
||||||
|
let client_id = "client1".to_string();
|
||||||
dsn.params.insert("auto.offset.reset".to_string(), "latest".to_string());
|
dsn.params.insert("auto.offset.reset".to_string(), "latest".to_string());
|
||||||
dsn.params.insert("msg.with.table.name".to_string(), "true".to_string());
|
dsn.params.insert("msg.with.table.name".to_string(), "true".to_string());
|
||||||
dsn.params.insert("enable.auto.commit".to_string(), "true".to_string());
|
dsn.params.insert("enable.auto.commit".to_string(), "true".to_string());
|
||||||
dsn.params.insert("auto.commit.interval.ms".to_string(), "1000".to_string());
|
dsn.params.insert("auto.commit.interval.ms".to_string(), "1000".to_string());
|
||||||
dsn.params.insert("group.id".to_string(), "group1".to_string());
|
dsn.params.insert("group.id".to_string(), group_id.clone());
|
||||||
dsn.params.insert("client.id".to_string(), "client1".to_string());
|
dsn.params.insert("client.id".to_string(), client_id.clone());
|
||||||
|
|
||||||
let builder = TmqBuilder::from_dsn(&dsn)?;
|
let builder = TmqBuilder::from_dsn(&dsn)?;
|
||||||
let mut consumer = builder.build().await?;
|
let mut consumer = match builder.build().await{
|
||||||
|
Ok(consumer) => {
|
||||||
|
println!("Create consumer successfully, dsn: {}, groupId: {}, clientId: {}.", dsn, group_id, client_id);
|
||||||
|
consumer
|
||||||
|
}
|
||||||
|
Err(err) => {
|
||||||
|
eprintln!("Failed to create consumer, dsn: {}; ErrMessage: {}", dsn, err);
|
||||||
|
return Err(err.into());
|
||||||
|
}
|
||||||
|
};
|
||||||
// ANCHOR_END: create_consumer_ac
|
// ANCHOR_END: create_consumer_ac
|
||||||
|
|
||||||
// ANCHOR: subscribe
|
// ANCHOR: consume
|
||||||
consumer.subscribe(["topic_meters"]).await?;
|
match consumer.subscribe(["topic_meters"]).await{
|
||||||
// ANCHOR_END: subscribe
|
Ok(_) => println!("Subscribe topics successfully."),
|
||||||
|
Err(err) => {
|
||||||
|
eprintln!("Failed to subscribe topic_meters, dsn: {}; ErrMessage: {}", dsn, err);
|
||||||
|
return Err(err.into());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Debug, serde::Deserialize)]
|
#[derive(Debug, serde::Deserialize)]
|
||||||
#[allow(dead_code)]
|
#[allow(dead_code)]
|
||||||
|
@ -67,8 +83,6 @@ async fn main() -> anyhow::Result<()> {
|
||||||
location: String,
|
location: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
// ANCHOR: consume
|
|
||||||
|
|
||||||
consumer
|
consumer
|
||||||
.stream()
|
.stream()
|
||||||
.try_for_each(|(offset, message)| async move {
|
.try_for_each(|(offset, message)| async move {
|
||||||
|
@ -85,7 +99,10 @@ async fn main() -> anyhow::Result<()> {
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
})
|
})
|
||||||
.await?;
|
.await.map_err(|e| {
|
||||||
|
eprintln!("Failed to execute consumer functions. ErrMessage: {:?}", e);
|
||||||
|
e
|
||||||
|
})?;
|
||||||
|
|
||||||
// ANCHOR_END: consume
|
// ANCHOR_END: consume
|
||||||
|
|
||||||
|
@ -105,16 +122,25 @@ async fn main() -> anyhow::Result<()> {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// commit offset manually when you have processed the message.
|
// commit offset manually when you have processed the message.
|
||||||
consumer.commit(offset).await?;
|
match consumer.commit(offset).await{
|
||||||
|
Ok(_) => println!("Commit offset manually successfully."),
|
||||||
|
Err(err) => {
|
||||||
|
eprintln!("Failed to commit offset manually, dsn: {}; ErrMessage: {}", dsn, err);
|
||||||
|
return Err(err.into());
|
||||||
|
}
|
||||||
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
})
|
})
|
||||||
.await?;
|
.await.map_err(|e| {
|
||||||
|
eprintln!("Failed to execute consumer functions. ErrMessage: {:?}", e);
|
||||||
|
e
|
||||||
|
})?;
|
||||||
// ANCHOR_END: consumer_commit_manually
|
// ANCHOR_END: consumer_commit_manually
|
||||||
|
|
||||||
// ANCHOR: assignments
|
|
||||||
|
// ANCHOR: seek_offset
|
||||||
let assignments = consumer.assignments().await.unwrap();
|
let assignments = consumer.assignments().await.unwrap();
|
||||||
log::info!("assignments: {:?}", assignments);
|
println!("Now assignments: {:?}", assignments);
|
||||||
// ANCHOR_END: assignments
|
|
||||||
|
|
||||||
// seek offset
|
// seek offset
|
||||||
for topic_vec_assignment in assignments {
|
for topic_vec_assignment in assignments {
|
||||||
|
@ -125,7 +151,7 @@ async fn main() -> anyhow::Result<()> {
|
||||||
let current = assignment.current_offset();
|
let current = assignment.current_offset();
|
||||||
let begin = assignment.begin();
|
let begin = assignment.begin();
|
||||||
let end = assignment.end();
|
let end = assignment.end();
|
||||||
log::debug!(
|
println!(
|
||||||
"topic: {}, vgroup_id: {}, current offset: {} begin {}, end: {}",
|
"topic: {}, vgroup_id: {}, current offset: {} begin {}, end: {}",
|
||||||
topic,
|
topic,
|
||||||
vgroup_id,
|
vgroup_id,
|
||||||
|
@ -133,26 +159,28 @@ async fn main() -> anyhow::Result<()> {
|
||||||
begin,
|
begin,
|
||||||
end
|
end
|
||||||
);
|
);
|
||||||
// ANCHOR: seek_offset
|
|
||||||
let res = consumer.offset_seek(topic, vgroup_id, end).await;
|
match consumer.offset_seek(topic, vgroup_id, begin).await{
|
||||||
if res.is_err() {
|
Ok(_) => (),
|
||||||
log::error!("seek offset error: {:?}", res);
|
Err(err) => {
|
||||||
let a = consumer.assignments().await.unwrap();
|
eprintln!("Seek example failed; ErrMessage: {}", err);
|
||||||
log::error!("assignments: {:?}", a);
|
return Err(err.into());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
// ANCHOR_END: seek_offset
|
|
||||||
}
|
}
|
||||||
|
|
||||||
let topic_assignment = consumer.topic_assignment(topic).await;
|
let topic_assignment = consumer.topic_assignment(topic).await;
|
||||||
log::debug!("topic assignment: {:?}", topic_assignment);
|
println!("Topic assignment: {:?}", topic_assignment);
|
||||||
}
|
}
|
||||||
|
println!("Assignment seek to beginning successfully.");
|
||||||
// after seek offset
|
// after seek offset
|
||||||
let assignments = consumer.assignments().await.unwrap();
|
let assignments = consumer.assignments().await.unwrap();
|
||||||
log::info!("after seek offset assignments: {:?}", assignments);
|
println!("After seek offset assignments: {:?}", assignments);
|
||||||
|
// ANCHOR_END: seek_offset
|
||||||
|
|
||||||
// ANCHOR: unsubscribe
|
// ANCHOR: unsubscribe
|
||||||
consumer.unsubscribe().await;
|
consumer.unsubscribe().await;
|
||||||
|
println!("Consumer unsubscribed successfully.");
|
||||||
// ANCHOR_END: unsubscribe
|
// ANCHOR_END: unsubscribe
|
||||||
|
|
||||||
tokio::time::sleep(Duration::from_secs(1)).await;
|
tokio::time::sleep(Duration::from_secs(1)).await;
|
||||||
|
|
|
@ -1,9 +1,17 @@
|
||||||
use taos::*;
|
use taos::*;
|
||||||
|
|
||||||
#[tokio::main]
|
#[tokio::main]
|
||||||
async fn main() -> Result<(), Error> {
|
async fn main() -> anyhow::Result<()> {
|
||||||
#[allow(unused_variables)]
|
let dsn = "ws://localhost:6041".to_string();
|
||||||
let taos = TaosBuilder::from_dsn("taos+ws://localhost:6041")?.build()?;
|
|
||||||
println!("Connected to localhost with websocket connection successfully.");
|
match TaosBuilder::from_dsn(&dsn)?.build().await {
|
||||||
Ok(())
|
Ok(_taos) => {
|
||||||
|
println!("Connected to {} successfully.", dsn);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
Err(err) => {
|
||||||
|
eprintln!("Failed to connect to {}; ErrMessage: {}", dsn, err);
|
||||||
|
return Err(err.into());
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -0,0 +1,35 @@
|
||||||
|
use taos::*;
|
||||||
|
|
||||||
|
#[tokio::main]
|
||||||
|
async fn main() -> anyhow::Result<()> {
|
||||||
|
let url = "ws://localhost:6041";
|
||||||
|
|
||||||
|
// ANCHOR: create_db_and_table
|
||||||
|
let taos = TaosBuilder::from_dsn(url)?.build().await?;
|
||||||
|
|
||||||
|
// create database and use it
|
||||||
|
match taos.exec_many([
|
||||||
|
"CREATE DATABASE IF NOT EXISTS power",
|
||||||
|
]).await {
|
||||||
|
Ok(afffected_rows) => println!("Create database power successfully, rowsAffected: {}", afffected_rows),
|
||||||
|
Err(err) => {
|
||||||
|
eprintln!("Failed to create database power; ErrMessage: {}", err);
|
||||||
|
return Err(err.into());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// create super table
|
||||||
|
match taos.exec_many([
|
||||||
|
"CREATE STABLE IF NOT EXISTS power.meters (`ts` TIMESTAMP, `current` FLOAT, `voltage` INT, `phase` FLOAT) \
|
||||||
|
TAGS (`groupid` INT, `location` BINARY(24))",
|
||||||
|
]).await {
|
||||||
|
Ok(afffected_rows) => println!("Create stable power.meters successfully, rowsAffected: {}", afffected_rows),
|
||||||
|
Err(err) => {
|
||||||
|
eprintln!("Failed to create stable power.meters; ErrMessage: {}", err);
|
||||||
|
return Err(err.into());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
// ANCHOR_END: create_db_and_table
|
||||||
|
}
|
|
@ -0,0 +1,31 @@
|
||||||
|
use taos::*;
|
||||||
|
|
||||||
|
#[tokio::main]
|
||||||
|
async fn main() -> anyhow::Result<()> {
|
||||||
|
let dsn = "ws://localhost:6041";
|
||||||
|
let builder = TaosBuilder::from_dsn(dsn)?;
|
||||||
|
|
||||||
|
let taos = builder.build().await?;
|
||||||
|
|
||||||
|
|
||||||
|
// ANCHOR: insert_data
|
||||||
|
match taos.exec(r#"INSERT INTO
|
||||||
|
power.d1001 USING power.meters 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 TAGS(3, 'California.SanFrancisco')
|
||||||
|
VALUES
|
||||||
|
(NOW + 1a, 10.30000, 218, 0.25000) "#).await{
|
||||||
|
Ok(affected_rows) => println!("Successfully inserted {} rows to power.meters.", affected_rows),
|
||||||
|
Err(err) => {
|
||||||
|
eprintln!("Failed to insert data to power.meters, dsn: {}; ErrMessage: {}", dsn, err);
|
||||||
|
return Err(err.into());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ANCHOR_END: insert_data
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
|
@ -0,0 +1,102 @@
|
||||||
|
use taos::*;
|
||||||
|
use chrono::Local;
|
||||||
|
use chrono::DateTime;
|
||||||
|
|
||||||
|
#[tokio::main]
|
||||||
|
async fn main() -> anyhow::Result<()> {
|
||||||
|
let dsn = "ws://localhost:6041";
|
||||||
|
let builder = TaosBuilder::from_dsn(dsn)?;
|
||||||
|
|
||||||
|
let taos = builder.build().await?;
|
||||||
|
|
||||||
|
// ANCHOR: query_data
|
||||||
|
// query data, make sure the database and table are created before
|
||||||
|
match taos.query("SELECT ts, current, location FROM power.meters limit 100").await{
|
||||||
|
Ok(mut result) => {
|
||||||
|
for field in result.fields() {
|
||||||
|
println!("got field: {}", field.name());
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut rows = result.rows();
|
||||||
|
let mut nrows = 0;
|
||||||
|
while let Some(row) = rows.try_next().await? {
|
||||||
|
for (col, (name, value)) in row.enumerate() {
|
||||||
|
println!(
|
||||||
|
"[{}] got value in col {} (named `{:>8}`): {}",
|
||||||
|
nrows, col, name, value
|
||||||
|
);
|
||||||
|
}
|
||||||
|
nrows += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(err) => {
|
||||||
|
eprintln!("Failed to query data from power.meters, dsn: {}; ErrMessage: {}", dsn, err);
|
||||||
|
return Err(err.into());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
// ANCHOR_END: query_data
|
||||||
|
|
||||||
|
// ANCHOR: query_data_2
|
||||||
|
// query data, make sure the database and table are created before
|
||||||
|
#[derive(Debug, serde::Deserialize)]
|
||||||
|
#[allow(dead_code)]
|
||||||
|
struct Record {
|
||||||
|
// deserialize timestamp to chrono::DateTime<Local>
|
||||||
|
ts: DateTime<Local>,
|
||||||
|
// float to f32
|
||||||
|
current: Option<f32>,
|
||||||
|
// binary/varchar to String
|
||||||
|
location: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
match taos.query("SELECT ts, current, location FROM power.meters limit 100").await {
|
||||||
|
Ok(mut query) => {
|
||||||
|
match query.deserialize::<Record>().try_collect::<Vec<_>>().await {
|
||||||
|
Ok(records) => {
|
||||||
|
dbg!(records);
|
||||||
|
}
|
||||||
|
Err(err) => {
|
||||||
|
eprintln!("Failed to deserialize query results; ErrMessage: {}", err);
|
||||||
|
return Err(err.into());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(err) => {
|
||||||
|
eprintln!("Failed to query data from power.meters, url: {}; ErrMessage: {}", dsn, err);
|
||||||
|
return Err(err.into());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// ANCHOR_END: query_data_2
|
||||||
|
|
||||||
|
// ANCHOR: query_with_req_id
|
||||||
|
|
||||||
|
let req_id :u64 = 3;
|
||||||
|
match taos.query_with_req_id("SELECT ts, current, location FROM power.meters limit 1", req_id).await{
|
||||||
|
Ok(mut result) => {
|
||||||
|
for field in result.fields() {
|
||||||
|
println!("got field: {}", field.name());
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut rows = result.rows();
|
||||||
|
let mut nrows = 0;
|
||||||
|
while let Some(row) = rows.try_next().await? {
|
||||||
|
for (col, (name, value)) in row.enumerate() {
|
||||||
|
println!(
|
||||||
|
"[{}] got value in col {} (named `{:>8}`): {}",
|
||||||
|
nrows, col, name, value
|
||||||
|
);
|
||||||
|
}
|
||||||
|
nrows += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(err) => {
|
||||||
|
eprintln!("Failed to execute sql with reqId: {}, dsn: {}; ErrMessage: {}", req_id, dsn, err);
|
||||||
|
return Err(err.into());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ANCHOR_END: query_with_req_id
|
||||||
|
Ok(())
|
||||||
|
}
|
|
@ -11,7 +11,8 @@ use taos::taos_query;
|
||||||
async fn main() -> anyhow::Result<()> {
|
async fn main() -> anyhow::Result<()> {
|
||||||
std::env::set_var("RUST_LOG", "taos=debug");
|
std::env::set_var("RUST_LOG", "taos=debug");
|
||||||
pretty_env_logger::init();
|
pretty_env_logger::init();
|
||||||
let dsn = "http://localhost:6041/power".to_string();
|
let host = "localhost";
|
||||||
|
let dsn = format!("ws://{}:6041/power", host);
|
||||||
log::debug!("dsn: {:?}", &dsn);
|
log::debug!("dsn: {:?}", &dsn);
|
||||||
|
|
||||||
let client = TaosBuilder::from_dsn(dsn)?.build().await?;
|
let client = TaosBuilder::from_dsn(dsn)?.build().await?;
|
||||||
|
@ -30,7 +31,13 @@ async fn main() -> anyhow::Result<()> {
|
||||||
.ttl(1000)
|
.ttl(1000)
|
||||||
.req_id(100u64)
|
.req_id(100u64)
|
||||||
.build()?;
|
.build()?;
|
||||||
assert_eq!(client.put(&sml_data).await?, ());
|
match client.put(&sml_data).await{
|
||||||
|
Ok(_) => {},
|
||||||
|
Err(err) => {
|
||||||
|
eprintln!("Failed to insert data with schemaless, host: {}; ErrMessage: {}", host, err);
|
||||||
|
return Err(err.into());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// SchemalessProtocol::Telnet
|
// SchemalessProtocol::Telnet
|
||||||
let data = [
|
let data = [
|
||||||
|
@ -46,7 +53,13 @@ async fn main() -> anyhow::Result<()> {
|
||||||
.ttl(1000)
|
.ttl(1000)
|
||||||
.req_id(200u64)
|
.req_id(200u64)
|
||||||
.build()?;
|
.build()?;
|
||||||
assert_eq!(client.put(&sml_data).await?, ());
|
match client.put(&sml_data).await{
|
||||||
|
Ok(_) => {},
|
||||||
|
Err(err) => {
|
||||||
|
eprintln!("Failed to insert data with schemaless, host: {}; ErrMessage: {}", host, err);
|
||||||
|
return Err(err.into());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// SchemalessProtocol::Json
|
// SchemalessProtocol::Json
|
||||||
let data = [
|
let data = [
|
||||||
|
@ -71,7 +84,13 @@ async fn main() -> anyhow::Result<()> {
|
||||||
.ttl(1000)
|
.ttl(1000)
|
||||||
.req_id(300u64)
|
.req_id(300u64)
|
||||||
.build()?;
|
.build()?;
|
||||||
assert_eq!(client.put(&sml_data).await?, ());
|
match client.put(&sml_data).await{
|
||||||
|
Ok(_) => {},
|
||||||
|
Err(err) => {
|
||||||
|
eprintln!("Failed to insert data with schemaless, host: {}; ErrMessage: {}", host, err);
|
||||||
|
return Err(err.into());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
println!("Inserted data with schemaless successfully.");
|
println!("Inserted data with schemaless successfully.");
|
||||||
Ok(())
|
Ok(())
|
||||||
|
|
|
@ -2,12 +2,13 @@ use taos::*;
|
||||||
|
|
||||||
#[tokio::main]
|
#[tokio::main]
|
||||||
async fn main() -> anyhow::Result<()> {
|
async fn main() -> anyhow::Result<()> {
|
||||||
let taos = TaosBuilder::from_dsn("ws://")?.build().await?;
|
let dsn = "ws://";
|
||||||
|
let taos = TaosBuilder::from_dsn(dsn)?.build().await?;
|
||||||
|
|
||||||
taos.exec("DROP DATABASE IF EXISTS power").await?;
|
taos.exec("DROP DATABASE IF EXISTS power").await?;
|
||||||
taos.create_database("power").await?;
|
taos.create_database("power").await?;
|
||||||
taos.use_database("power").await?;
|
taos.use_database("power").await?;
|
||||||
taos.exec("CREATE STABLE IF NOT EXISTS meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (location BINARY(64), groupId INT)").await?;
|
taos.exec("CREATE STABLE IF NOT EXISTS power.meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (groupId INT, location BINARY(24))").await?;
|
||||||
|
|
||||||
let mut stmt = Stmt::init(&taos).await?;
|
let mut stmt = Stmt::init(&taos).await?;
|
||||||
stmt.prepare("INSERT INTO ? USING meters TAGS(?, ?) VALUES(?, ?, ?, ?)").await?;
|
stmt.prepare("INSERT INTO ? USING meters TAGS(?, ?) VALUES(?, ?, ?, ?)").await?;
|
||||||
|
@ -15,8 +16,8 @@ async fn main() -> anyhow::Result<()> {
|
||||||
const NUM_TABLES: usize = 10;
|
const NUM_TABLES: usize = 10;
|
||||||
const NUM_ROWS: usize = 10;
|
const NUM_ROWS: usize = 10;
|
||||||
for i in 0..NUM_TABLES {
|
for i in 0..NUM_TABLES {
|
||||||
let table_name = format!("d{}", i);
|
let table_name = format!("d_bind_{}", i);
|
||||||
let tags = vec![Value::VarChar("California.SanFransico".into()), Value::Int(2)];
|
let tags = vec![Value::Int(i as i32), Value::VarChar(format!("location_{}", i).into())];
|
||||||
|
|
||||||
// set table name and tags for the prepared statement.
|
// set table name and tags for the prepared statement.
|
||||||
stmt.set_tbname_tags(&table_name, &tags).await?;
|
stmt.set_tbname_tags(&table_name, &tags).await?;
|
||||||
|
@ -35,9 +36,13 @@ async fn main() -> anyhow::Result<()> {
|
||||||
}
|
}
|
||||||
|
|
||||||
// execute.
|
// execute.
|
||||||
let rows = stmt.execute().await?;
|
match stmt.execute().await{
|
||||||
assert_eq!(rows, NUM_TABLES * NUM_ROWS);
|
Ok(affected_rows) => println!("Successfully inserted {} rows to power.meters.", affected_rows),
|
||||||
|
Err(err) => {
|
||||||
println!("execute stmt insert successfully");
|
eprintln!("Failed to insert to table meters using stmt, dsn: {}; ErrMessage: {}", dsn, err);
|
||||||
|
return Err(err.into());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
|
@ -12,7 +12,7 @@ async fn main() -> anyhow::Result<()> {
|
||||||
use taos_query::prelude::*;
|
use taos_query::prelude::*;
|
||||||
// ANCHOR: create_consumer_dsn
|
// ANCHOR: create_consumer_dsn
|
||||||
let dsn = "ws://localhost:6041".to_string();
|
let dsn = "ws://localhost:6041".to_string();
|
||||||
log::info!("dsn: {}", dsn);
|
println!("dsn: {}", dsn);
|
||||||
let mut dsn = Dsn::from_str(&dsn)?;
|
let mut dsn = Dsn::from_str(&dsn)?;
|
||||||
// ANCHOR_END: create_consumer_dsn
|
// ANCHOR_END: create_consumer_dsn
|
||||||
|
|
||||||
|
@ -37,20 +37,36 @@ async fn main() -> anyhow::Result<()> {
|
||||||
// ANCHOR_END: create_topic
|
// ANCHOR_END: create_topic
|
||||||
|
|
||||||
// ANCHOR: create_consumer_ac
|
// ANCHOR: create_consumer_ac
|
||||||
|
let group_id = "group1".to_string();
|
||||||
|
let client_id = "client1".to_string();
|
||||||
dsn.params.insert("auto.offset.reset".to_string(), "latest".to_string());
|
dsn.params.insert("auto.offset.reset".to_string(), "latest".to_string());
|
||||||
dsn.params.insert("msg.with.table.name".to_string(), "true".to_string());
|
dsn.params.insert("msg.with.table.name".to_string(), "true".to_string());
|
||||||
dsn.params.insert("enable.auto.commit".to_string(), "true".to_string());
|
dsn.params.insert("enable.auto.commit".to_string(), "true".to_string());
|
||||||
dsn.params.insert("auto.commit.interval.ms".to_string(), "1000".to_string());
|
dsn.params.insert("auto.commit.interval.ms".to_string(), "1000".to_string());
|
||||||
dsn.params.insert("group.id".to_string(), "group1".to_string());
|
dsn.params.insert("group.id".to_string(), group_id.clone());
|
||||||
dsn.params.insert("client.id".to_string(), "client1".to_string());
|
dsn.params.insert("client.id".to_string(), client_id.clone());
|
||||||
|
|
||||||
let builder = TmqBuilder::from_dsn(&dsn)?;
|
let builder = TmqBuilder::from_dsn(&dsn)?;
|
||||||
let mut consumer = builder.build().await?;
|
let mut consumer = match builder.build().await{
|
||||||
|
Ok(consumer) => {
|
||||||
|
println!("Create consumer successfully, dsn: {}, groupId: {}, clientId: {}.", dsn, group_id, client_id);
|
||||||
|
consumer
|
||||||
|
}
|
||||||
|
Err(err) => {
|
||||||
|
eprintln!("Failed to create consumer, dsn: {}; ErrMessage: {}", dsn, err);
|
||||||
|
return Err(err.into());
|
||||||
|
}
|
||||||
|
};
|
||||||
// ANCHOR_END: create_consumer_ac
|
// ANCHOR_END: create_consumer_ac
|
||||||
|
|
||||||
// ANCHOR: subscribe
|
// ANCHOR: consume
|
||||||
consumer.subscribe(["topic_meters"]).await?;
|
match consumer.subscribe(["topic_meters"]).await{
|
||||||
// ANCHOR_END: subscribe
|
Ok(_) => println!("Subscribe topics successfully."),
|
||||||
|
Err(err) => {
|
||||||
|
eprintln!("Failed to subscribe topic_meters, dsn: {}; ErrMessage: {}", dsn, err);
|
||||||
|
return Err(err.into());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Debug, serde::Deserialize)]
|
#[derive(Debug, serde::Deserialize)]
|
||||||
#[allow(dead_code)]
|
#[allow(dead_code)]
|
||||||
|
@ -67,8 +83,6 @@ async fn main() -> anyhow::Result<()> {
|
||||||
location: String,
|
location: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
// ANCHOR: consume
|
|
||||||
|
|
||||||
consumer
|
consumer
|
||||||
.stream()
|
.stream()
|
||||||
.try_for_each(|(offset, message)| async move {
|
.try_for_each(|(offset, message)| async move {
|
||||||
|
@ -85,7 +99,10 @@ async fn main() -> anyhow::Result<()> {
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
})
|
})
|
||||||
.await?;
|
.await.map_err(|e| {
|
||||||
|
eprintln!("Failed to poll data; ErrMessage: {:?}", e);
|
||||||
|
e
|
||||||
|
})?;
|
||||||
|
|
||||||
// ANCHOR_END: consume
|
// ANCHOR_END: consume
|
||||||
|
|
||||||
|
@ -105,16 +122,25 @@ async fn main() -> anyhow::Result<()> {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// commit offset manually when you have processed the message.
|
// commit offset manually when you have processed the message.
|
||||||
consumer.commit(offset).await?;
|
match consumer.commit(offset).await{
|
||||||
|
Ok(_) => println!("Commit offset manually successfully."),
|
||||||
|
Err(err) => {
|
||||||
|
eprintln!("Failed to commit offset manually, dsn: {}; ErrMessage: {}", dsn, err);
|
||||||
|
return Err(err.into());
|
||||||
|
}
|
||||||
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
})
|
})
|
||||||
.await?;
|
.await.map_err(|e| {
|
||||||
|
eprintln!("Failed to execute consumer functions. ErrMessage: {:?}", e);
|
||||||
|
e
|
||||||
|
})?;
|
||||||
// ANCHOR_END: consumer_commit_manually
|
// ANCHOR_END: consumer_commit_manually
|
||||||
|
|
||||||
// ANCHOR: assignments
|
|
||||||
|
// ANCHOR: seek_offset
|
||||||
let assignments = consumer.assignments().await.unwrap();
|
let assignments = consumer.assignments().await.unwrap();
|
||||||
log::info!("assignments: {:?}", assignments);
|
println!("assignments: {:?}", assignments);
|
||||||
// ANCHOR_END: assignments
|
|
||||||
|
|
||||||
// seek offset
|
// seek offset
|
||||||
for topic_vec_assignment in assignments {
|
for topic_vec_assignment in assignments {
|
||||||
|
@ -125,7 +151,7 @@ async fn main() -> anyhow::Result<()> {
|
||||||
let current = assignment.current_offset();
|
let current = assignment.current_offset();
|
||||||
let begin = assignment.begin();
|
let begin = assignment.begin();
|
||||||
let end = assignment.end();
|
let end = assignment.end();
|
||||||
log::debug!(
|
println!(
|
||||||
"topic: {}, vgroup_id: {}, current offset: {} begin {}, end: {}",
|
"topic: {}, vgroup_id: {}, current offset: {} begin {}, end: {}",
|
||||||
topic,
|
topic,
|
||||||
vgroup_id,
|
vgroup_id,
|
||||||
|
@ -133,26 +159,28 @@ async fn main() -> anyhow::Result<()> {
|
||||||
begin,
|
begin,
|
||||||
end
|
end
|
||||||
);
|
);
|
||||||
// ANCHOR: seek_offset
|
|
||||||
let res = consumer.offset_seek(topic, vgroup_id, end).await;
|
match consumer.offset_seek(topic, vgroup_id, begin).await{
|
||||||
if res.is_err() {
|
Ok(_) => (),
|
||||||
log::error!("seek offset error: {:?}", res);
|
Err(err) => {
|
||||||
let a = consumer.assignments().await.unwrap();
|
eprintln!("seek example failed; ErrMessage: {}", err);
|
||||||
log::error!("assignments: {:?}", a);
|
return Err(err.into());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
// ANCHOR_END: seek_offset
|
|
||||||
}
|
}
|
||||||
|
|
||||||
let topic_assignment = consumer.topic_assignment(topic).await;
|
let topic_assignment = consumer.topic_assignment(topic).await;
|
||||||
log::debug!("topic assignment: {:?}", topic_assignment);
|
println!("topic assignment: {:?}", topic_assignment);
|
||||||
}
|
}
|
||||||
|
println!("Assignment seek to beginning successfully.");
|
||||||
// after seek offset
|
// after seek offset
|
||||||
let assignments = consumer.assignments().await.unwrap();
|
let assignments = consumer.assignments().await.unwrap();
|
||||||
log::info!("after seek offset assignments: {:?}", assignments);
|
println!("After seek offset assignments: {:?}", assignments);
|
||||||
|
// ANCHOR_END: seek_offset
|
||||||
|
|
||||||
// ANCHOR: unsubscribe
|
// ANCHOR: unsubscribe
|
||||||
consumer.unsubscribe().await;
|
consumer.unsubscribe().await;
|
||||||
|
println!("Consumer unsubscribed successfully.");
|
||||||
// ANCHOR_END: unsubscribe
|
// ANCHOR_END: unsubscribe
|
||||||
|
|
||||||
tokio::time::sleep(Duration::from_secs(1)).await;
|
tokio::time::sleep(Duration::from_secs(1)).await;
|
||||||
|
|
|
@ -53,7 +53,7 @@ REST API:直接调用 `taosadapter` 提供的 REST API 接口,进行数据
|
||||||
<TabItem label="Rust" value="rust">
|
<TabItem label="Rust" value="rust">
|
||||||
|
|
||||||
```rust
|
```rust
|
||||||
{{#include docs/examples/rust/nativeexample/examples/query.rs:create_db_and_table}}
|
{{#include docs/examples/rust/nativeexample/examples/createdb.rs:create_db_and_table}}
|
||||||
```
|
```
|
||||||
|
|
||||||
</TabItem>
|
</TabItem>
|
||||||
|
@ -129,7 +129,7 @@ NOW 为系统内部函数,默认为客户端所在计算机当前时间。 NOW
|
||||||
<TabItem label="Rust" value="rust">
|
<TabItem label="Rust" value="rust">
|
||||||
|
|
||||||
```rust
|
```rust
|
||||||
{{#include docs/examples/rust/nativeexample/examples/query.rs:insert_data}}
|
{{#include docs/examples/rust/nativeexample/examples/insert.rs:insert_data}}
|
||||||
```
|
```
|
||||||
|
|
||||||
</TabItem>
|
</TabItem>
|
||||||
|
|
|
@ -37,13 +37,15 @@ public class ConsumerLoopFull {
|
||||||
config.setProperty("value.deserializer.encoding", "UTF-8");
|
config.setProperty("value.deserializer.encoding", "UTF-8");
|
||||||
|
|
||||||
try {
|
try {
|
||||||
return new TaosConsumer<>(config);
|
TaosConsumer<ResultBean> consumer= new TaosConsumer<>(config);
|
||||||
|
System.out.println("Create consumer successfully, host: " + config.getProperty("bootstrap.servers") + ", groupId: " + config.getProperty("group.id") + ", clientId: " + config.getProperty("client.id"));
|
||||||
|
return consumer;
|
||||||
} catch (SQLException ex) {
|
} catch (SQLException ex) {
|
||||||
// handle any errors, please refer to the JDBC specifications for detailed exceptions info
|
// handle any errors, please refer to the JDBC specifications for detailed exceptions info
|
||||||
System.out.println("Failed to create websocket consumer, host : " + config.getProperty("bootstrap.servers") + "; ErrCode:" + ex.getErrorCode() + "; ErrMessage: " + ex.getMessage());
|
System.out.println("Failed to create native consumer, host: " + config.getProperty("bootstrap.servers") + "; ErrCode:" + ex.getErrorCode() + "; ErrMessage: " + ex.getMessage());
|
||||||
throw new SQLException("Failed to create consumer", ex);
|
throw new SQLException("Failed to create consumer", ex);
|
||||||
} catch (Exception ex) {
|
} catch (Exception ex) {
|
||||||
System.out.println("Failed to create websocket consumer, host : " + config.getProperty("bootstrap.servers")
|
System.out.println("Failed to create native consumer, host: " + config.getProperty("bootstrap.servers")
|
||||||
+ "; ErrMessage: " + ex.getMessage());
|
+ "; ErrMessage: " + ex.getMessage());
|
||||||
throw new SQLException("Failed to create consumer", ex);
|
throw new SQLException("Failed to create consumer", ex);
|
||||||
}
|
}
|
||||||
|
@ -57,7 +59,7 @@ public class ConsumerLoopFull {
|
||||||
|
|
||||||
// subscribe to the topics
|
// subscribe to the topics
|
||||||
consumer.subscribe(topics);
|
consumer.subscribe(topics);
|
||||||
System.out.println("subscribe topics successfully");
|
System.out.println("Subscribe topics successfully.");
|
||||||
for (int i = 0; i < 50; i++) {
|
for (int i = 0; i < 50; i++) {
|
||||||
// poll data
|
// poll data
|
||||||
ConsumerRecords<ResultBean> records = consumer.poll(Duration.ofMillis(100));
|
ConsumerRecords<ResultBean> records = consumer.poll(Duration.ofMillis(100));
|
||||||
|
@ -70,10 +72,10 @@ public class ConsumerLoopFull {
|
||||||
|
|
||||||
} catch (SQLException ex) {
|
} catch (SQLException ex) {
|
||||||
// handle any errors, please refer to the JDBC specifications for detailed exceptions info
|
// handle any errors, please refer to the JDBC specifications for detailed exceptions info
|
||||||
System.out.println("Failed to poll data; ErrCode:" + ex.getErrorCode() + "; ErrMessage: " + ex.getMessage());
|
System.out.println("Failed to poll data, ErrCode:" + ex.getErrorCode() + "; ErrMessage: " + ex.getMessage());
|
||||||
throw new SQLException("Failed to poll data", ex);
|
throw new SQLException("Failed to poll data", ex);
|
||||||
} catch (Exception ex) {
|
} catch (Exception ex) {
|
||||||
System.out.println("Failed to poll data; ErrMessage: " + ex.getMessage());
|
System.out.println("Failed to poll data, ErrMessage: " + ex.getMessage());
|
||||||
throw new SQLException("Failed to poll data", ex);
|
throw new SQLException("Failed to poll data", ex);
|
||||||
}
|
}
|
||||||
// ANCHOR_END: poll_data_code_piece
|
// ANCHOR_END: poll_data_code_piece
|
||||||
|
@ -86,9 +88,9 @@ public class ConsumerLoopFull {
|
||||||
|
|
||||||
// subscribe to the topics
|
// subscribe to the topics
|
||||||
consumer.subscribe(topics);
|
consumer.subscribe(topics);
|
||||||
System.out.println("subscribe topics successfully");
|
System.out.println("Subscribe topics successfully.");
|
||||||
Set<TopicPartition> assignment = consumer.assignment();
|
Set<TopicPartition> assignment = consumer.assignment();
|
||||||
System.out.println("now assignment: " + JSON.toJSONString(assignment));
|
System.out.println("Now assignment: " + JSON.toJSONString(assignment));
|
||||||
|
|
||||||
ConsumerRecords<ResultBean> records = ConsumerRecords.emptyRecord();
|
ConsumerRecords<ResultBean> records = ConsumerRecords.emptyRecord();
|
||||||
// make sure we have got some data
|
// make sure we have got some data
|
||||||
|
@ -97,14 +99,13 @@ public class ConsumerLoopFull {
|
||||||
}
|
}
|
||||||
|
|
||||||
consumer.seekToBeginning(assignment);
|
consumer.seekToBeginning(assignment);
|
||||||
System.out.println("assignment seek to beginning successfully");
|
System.out.println("Assignment seek to beginning successfully.");
|
||||||
System.out.println("beginning assignment: " + JSON.toJSONString(assignment));
|
|
||||||
} catch (SQLException ex) {
|
} catch (SQLException ex) {
|
||||||
// handle any errors, please refer to the JDBC specifications for detailed exceptions info
|
// handle any errors, please refer to the JDBC specifications for detailed exceptions info
|
||||||
System.out.println("seek example failed; ErrCode:" + ex.getErrorCode() + "; ErrMessage: " + ex.getMessage());
|
System.out.println("Seek example failed; ErrCode:" + ex.getErrorCode() + "; ErrMessage: " + ex.getMessage());
|
||||||
throw new SQLException("seek example failed", ex);
|
throw new SQLException("seek example failed", ex);
|
||||||
} catch (Exception ex) {
|
} catch (Exception ex) {
|
||||||
System.out.println("seek example failed; ErrMessage: " + ex.getMessage());
|
System.out.println("Seek example failed; ErrMessage: " + ex.getMessage());
|
||||||
throw new SQLException("seek example failed", ex);
|
throw new SQLException("seek example failed", ex);
|
||||||
}
|
}
|
||||||
// ANCHOR_END: consumer_seek
|
// ANCHOR_END: consumer_seek
|
||||||
|
@ -127,6 +128,7 @@ public class ConsumerLoopFull {
|
||||||
if (!records.isEmpty()) {
|
if (!records.isEmpty()) {
|
||||||
// after processing the data, commit the offset manually
|
// after processing the data, commit the offset manually
|
||||||
consumer.commitSync();
|
consumer.commitSync();
|
||||||
|
System.out.println("Commit offset manually successfully.");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch (SQLException ex) {
|
} catch (SQLException ex) {
|
||||||
|
@ -147,6 +149,7 @@ public class ConsumerLoopFull {
|
||||||
try {
|
try {
|
||||||
// unsubscribe the consumer
|
// unsubscribe the consumer
|
||||||
consumer.unsubscribe();
|
consumer.unsubscribe();
|
||||||
|
System.out.println("Consumer unsubscribed successfully.");
|
||||||
} catch (SQLException ex) {
|
} catch (SQLException ex) {
|
||||||
// handle any errors, please refer to the JDBC specifications for detailed exceptions info
|
// handle any errors, please refer to the JDBC specifications for detailed exceptions info
|
||||||
System.out.println("Failed to unsubscribe consumer. ErrCode:" + ex.getErrorCode() + "; ErrMessage: " + ex.getMessage());
|
System.out.println("Failed to unsubscribe consumer. ErrCode:" + ex.getErrorCode() + "; ErrMessage: " + ex.getMessage());
|
||||||
|
@ -158,6 +161,7 @@ public class ConsumerLoopFull {
|
||||||
finally {
|
finally {
|
||||||
// close the consumer
|
// close the consumer
|
||||||
consumer.close();
|
consumer.close();
|
||||||
|
System.out.println("Consumer closed successfully.");
|
||||||
}
|
}
|
||||||
// ANCHOR_END: unsubscribe_data_code_piece
|
// ANCHOR_END: unsubscribe_data_code_piece
|
||||||
}
|
}
|
||||||
|
@ -313,22 +317,22 @@ public class ConsumerLoopFull {
|
||||||
System.out.println("Failed to prepare data, ErrMessage: " + ex.getMessage());
|
System.out.println("Failed to prepare data, ErrMessage: " + ex.getMessage());
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
System.out.println("pollDataExample executed successfully");
|
System.out.println("pollDataExample executed successfully.");
|
||||||
});
|
});
|
||||||
|
|
||||||
try {
|
try {
|
||||||
TaosConsumer<ResultBean> consumer = getConsumer();
|
TaosConsumer<ResultBean> consumer = getConsumer();
|
||||||
|
|
||||||
pollExample(consumer);
|
pollExample(consumer);
|
||||||
System.out.println("pollExample executed successfully");
|
System.out.println("pollExample executed successfully.");
|
||||||
consumer.unsubscribe();
|
consumer.unsubscribe();
|
||||||
|
|
||||||
seekExample(consumer);
|
seekExample(consumer);
|
||||||
System.out.println("seekExample executed successfully");
|
System.out.println("seekExample executed successfully.");
|
||||||
consumer.unsubscribe();
|
consumer.unsubscribe();
|
||||||
|
|
||||||
commitExample(consumer);
|
commitExample(consumer);
|
||||||
System.out.println("commitExample executed successfully");
|
System.out.println("commitExample executed successfully.");
|
||||||
consumer.unsubscribe();
|
consumer.unsubscribe();
|
||||||
|
|
||||||
unsubscribeExample(consumer);
|
unsubscribeExample(consumer);
|
||||||
|
|
|
@ -30,17 +30,11 @@ public class JdbcCreatDBDemo {
|
||||||
// create database
|
// create database
|
||||||
int rowsAffected = stmt.executeUpdate("CREATE DATABASE IF NOT EXISTS power");
|
int rowsAffected = stmt.executeUpdate("CREATE DATABASE IF NOT EXISTS power");
|
||||||
// you can check rowsAffected here
|
// you can check rowsAffected here
|
||||||
assert rowsAffected == 0;
|
System.out.println("Create database power successfully, rowsAffected: " + rowsAffected);
|
||||||
|
|
||||||
// use database
|
|
||||||
rowsAffected = stmt.executeUpdate("USE power");
|
|
||||||
// you can check rowsAffected here
|
|
||||||
assert rowsAffected == 0;
|
|
||||||
|
|
||||||
// create table
|
// create table
|
||||||
rowsAffected = stmt.executeUpdate("CREATE STABLE IF NOT EXISTS meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (groupId INT, location BINARY(24))");
|
rowsAffected = stmt.executeUpdate("CREATE STABLE IF NOT EXISTS power.meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (groupId INT, location BINARY(24))");
|
||||||
// you can check rowsAffected here
|
// you can check rowsAffected here
|
||||||
assert rowsAffected == 0;
|
System.out.println("Create stable power.meters successfully, rowsAffected: " + rowsAffected);
|
||||||
|
|
||||||
} catch (SQLException ex) {
|
} catch (SQLException ex) {
|
||||||
// handle any errors, please refer to the JDBC specifications for detailed exceptions info
|
// handle any errors, please refer to the JDBC specifications for detailed exceptions info
|
||||||
|
|
|
@ -39,7 +39,7 @@ public class JdbcInsertDataDemo {
|
||||||
"(NOW + 1a, 10.30000, 218, 0.25000) ";
|
"(NOW + 1a, 10.30000, 218, 0.25000) ";
|
||||||
int affectedRows = stmt.executeUpdate(insertQuery);
|
int affectedRows = stmt.executeUpdate(insertQuery);
|
||||||
// you can check affectedRows here
|
// you can check affectedRows here
|
||||||
System.out.println("inserted into " + affectedRows + " rows to power.meters successfully.");
|
System.out.println("Successfully inserted " + affectedRows + " rows to power.meters.");
|
||||||
} catch (SQLException ex) {
|
} catch (SQLException ex) {
|
||||||
// handle any errors, please refer to the JDBC specifications for detailed exceptions info
|
// handle any errors, please refer to the JDBC specifications for detailed exceptions info
|
||||||
System.out.println("Failed to insert data to power.meters, url:" + jdbcUrl + "; ErrCode:" + ex.getErrorCode() + "; ErrMessage: " + ex.getMessage());
|
System.out.println("Failed to insert data to power.meters, url:" + jdbcUrl + "; ErrCode:" + ex.getErrorCode() + "; ErrMessage: " + ex.getMessage());
|
||||||
|
|
|
@ -25,22 +25,32 @@ public class JdbcReqIdDemo {
|
||||||
System.out.println("get connection starting...");
|
System.out.println("get connection starting...");
|
||||||
|
|
||||||
// ANCHOR: with_reqid
|
// ANCHOR: with_reqid
|
||||||
|
long reqId = 3L;
|
||||||
try (Connection connection = DriverManager.getConnection(jdbcUrl, properties);
|
try (Connection connection = DriverManager.getConnection(jdbcUrl, properties);
|
||||||
// Create a statement that allows specifying a request ID
|
// Create a statement that allows specifying a request ID
|
||||||
AbstractStatement aStmt = (AbstractStatement) connection.createStatement()) {
|
AbstractStatement aStmt = (AbstractStatement) connection.createStatement()) {
|
||||||
|
|
||||||
try (ResultSet rs = aStmt.executeQuery("SELECT ts, current, location FROM power.meters limit 1", 3L)) {
|
try (ResultSet resultSet = aStmt.executeQuery("SELECT ts, current, location FROM power.meters limit 1", reqId)) {
|
||||||
while (rs.next()) {
|
Timestamp ts;
|
||||||
Timestamp timestamp = rs.getTimestamp(1);
|
float current;
|
||||||
System.out.println("timestamp = " + timestamp);
|
String location;
|
||||||
|
while (resultSet.next()) {
|
||||||
|
ts = resultSet.getTimestamp(1);
|
||||||
|
current = resultSet.getFloat(2);
|
||||||
|
// we recommend using the column name to get the value
|
||||||
|
location = resultSet.getString("location");
|
||||||
|
|
||||||
|
// you can check data here
|
||||||
|
System.out.printf("ts: %s, current: %f, location: %s %n", ts, current, location);
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch (SQLException ex) {
|
} catch (SQLException ex) {
|
||||||
// handle any errors, please refer to the JDBC specifications for detailed exceptions info
|
// handle any errors, please refer to the JDBC specifications for detailed exceptions info
|
||||||
System.out.println("Failed to execute sql with reqId, url:" + jdbcUrl + "; ErrCode:" + ex.getErrorCode() + "; ErrMessage: " + ex.getMessage());
|
System.out.println("Failed to execute sql with reqId: " + reqId + ", url:" + jdbcUrl + "; ErrCode:" + ex.getErrorCode() + "; ErrMessage: " + ex.getMessage());
|
||||||
throw ex;
|
throw ex;
|
||||||
} catch (Exception ex){
|
} catch (Exception ex){
|
||||||
System.out.println("Failed to execute sql with reqId, url:" + jdbcUrl + "; ErrMessage: " + ex.getMessage());
|
System.out.println("Failed to execute sql with reqId: " + reqId + ", url:" + jdbcUrl + "; ErrMessage: " + ex.getMessage());
|
||||||
throw ex;
|
throw ex;
|
||||||
}
|
}
|
||||||
// ANCHOR_END: with_reqid
|
// ANCHOR_END: with_reqid
|
||||||
|
|
|
@ -24,7 +24,7 @@ public class ParameterBindingBasicDemo {
|
||||||
|
|
||||||
init(conn);
|
init(conn);
|
||||||
|
|
||||||
String sql = "INSERT INTO ? USING meters TAGS(?,?) VALUES (?,?,?,?)";
|
String sql = "INSERT INTO ? USING power.meters TAGS(?,?) VALUES (?,?,?,?)";
|
||||||
|
|
||||||
try (TSDBPreparedStatement pstmt = conn.prepareStatement(sql).unwrap(TSDBPreparedStatement.class)) {
|
try (TSDBPreparedStatement pstmt = conn.prepareStatement(sql).unwrap(TSDBPreparedStatement.class)) {
|
||||||
|
|
||||||
|
@ -65,6 +65,8 @@ public class ParameterBindingBasicDemo {
|
||||||
}
|
}
|
||||||
// execute column
|
// execute column
|
||||||
pstmt.columnDataExecuteBatch();
|
pstmt.columnDataExecuteBatch();
|
||||||
|
// you can check exeResult here
|
||||||
|
System.out.println("Successfully inserted " + (numOfSubTable * numOfRow) + " rows to power.meters.");
|
||||||
}
|
}
|
||||||
} catch (SQLException ex) {
|
} catch (SQLException ex) {
|
||||||
// handle any errors, please refer to the JDBC specifications for detailed exceptions info
|
// handle any errors, please refer to the JDBC specifications for detailed exceptions info
|
||||||
|
|
|
@ -21,7 +21,7 @@ public class WSParameterBindingBasicDemo {
|
||||||
try (Connection conn = DriverManager.getConnection(jdbcUrl, "root", "taosdata")) {
|
try (Connection conn = DriverManager.getConnection(jdbcUrl, "root", "taosdata")) {
|
||||||
init(conn);
|
init(conn);
|
||||||
|
|
||||||
String sql = "INSERT INTO ? USING meters TAGS(?,?) VALUES (?,?,?,?)";
|
String sql = "INSERT INTO ? USING power.meters TAGS(?,?) VALUES (?,?,?,?)";
|
||||||
|
|
||||||
try (TSWSPreparedStatement pstmt = conn.prepareStatement(sql).unwrap(TSWSPreparedStatement.class)) {
|
try (TSWSPreparedStatement pstmt = conn.prepareStatement(sql).unwrap(TSWSPreparedStatement.class)) {
|
||||||
|
|
||||||
|
@ -44,7 +44,7 @@ public class WSParameterBindingBasicDemo {
|
||||||
}
|
}
|
||||||
int [] exeResult = pstmt.executeBatch();
|
int [] exeResult = pstmt.executeBatch();
|
||||||
// you can check exeResult here
|
// you can check exeResult here
|
||||||
System.out.println("insert " + exeResult.length + " rows.");
|
System.out.println("Successfully inserted " + exeResult.length + " rows to power.meters.");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch (SQLException ex) {
|
} catch (SQLException ex) {
|
||||||
|
@ -61,7 +61,7 @@ public class WSParameterBindingBasicDemo {
|
||||||
try (Statement stmt = conn.createStatement()) {
|
try (Statement stmt = conn.createStatement()) {
|
||||||
stmt.execute("CREATE DATABASE IF NOT EXISTS power");
|
stmt.execute("CREATE DATABASE IF NOT EXISTS power");
|
||||||
stmt.execute("USE power");
|
stmt.execute("USE power");
|
||||||
stmt.execute("CREATE STABLE IF NOT EXISTS meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (groupId INT, location BINARY(24))");
|
stmt.execute("CREATE STABLE IF NOT EXISTS power.meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (groupId INT, location BINARY(24))");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -10,6 +10,7 @@ import java.util.*;
|
||||||
import java.util.concurrent.ExecutorService;
|
import java.util.concurrent.ExecutorService;
|
||||||
import java.util.concurrent.Executors;
|
import java.util.concurrent.Executors;
|
||||||
import java.util.concurrent.TimeUnit;
|
import java.util.concurrent.TimeUnit;
|
||||||
|
import java.util.function.Consumer;
|
||||||
|
|
||||||
// ANCHOR: consumer_demo
|
// ANCHOR: consumer_demo
|
||||||
public class WsConsumerLoopFull {
|
public class WsConsumerLoopFull {
|
||||||
|
@ -34,13 +35,15 @@ public class WsConsumerLoopFull {
|
||||||
config.setProperty("value.deserializer.encoding", "UTF-8");
|
config.setProperty("value.deserializer.encoding", "UTF-8");
|
||||||
|
|
||||||
try {
|
try {
|
||||||
return new TaosConsumer<>(config);
|
TaosConsumer<ResultBean> consumer= new TaosConsumer<>(config);
|
||||||
|
System.out.println("Create consumer successfully, host: " + config.getProperty("bootstrap.servers") + ", groupId: " + config.getProperty("group.id") + ", clientId: " + config.getProperty("client.id"));
|
||||||
|
return consumer;
|
||||||
} catch (SQLException ex) {
|
} catch (SQLException ex) {
|
||||||
// handle any errors, please refer to the JDBC specifications for detailed exceptions info
|
// handle any errors, please refer to the JDBC specifications for detailed exceptions info
|
||||||
System.out.println("Failed to create websocket consumer, host : " + config.getProperty("bootstrap.servers") + "; ErrCode:" + ex.getErrorCode() + "; ErrMessage: " + ex.getMessage());
|
System.out.println("Failed to create websocket consumer, host: " + config.getProperty("bootstrap.servers") + "; ErrCode:" + ex.getErrorCode() + "; ErrMessage: " + ex.getMessage());
|
||||||
throw new SQLException("Failed to create consumer", ex);
|
throw new SQLException("Failed to create consumer", ex);
|
||||||
} catch (Exception ex) {
|
} catch (Exception ex) {
|
||||||
System.out.println("Failed to create websocket consumer, host : " + config.getProperty("bootstrap.servers")
|
System.out.println("Failed to create websocket consumer, host: " + config.getProperty("bootstrap.servers")
|
||||||
+ "; ErrMessage: " + ex.getMessage());
|
+ "; ErrMessage: " + ex.getMessage());
|
||||||
throw new SQLException("Failed to create consumer", ex);
|
throw new SQLException("Failed to create consumer", ex);
|
||||||
}
|
}
|
||||||
|
@ -54,7 +57,7 @@ public class WsConsumerLoopFull {
|
||||||
|
|
||||||
// subscribe to the topics
|
// subscribe to the topics
|
||||||
consumer.subscribe(topics);
|
consumer.subscribe(topics);
|
||||||
System.out.println("subscribe topics successfully");
|
System.out.println("Subscribe topics successfully.");
|
||||||
for (int i = 0; i < 50; i++) {
|
for (int i = 0; i < 50; i++) {
|
||||||
// poll data
|
// poll data
|
||||||
ConsumerRecords<ResultBean> records = consumer.poll(Duration.ofMillis(100));
|
ConsumerRecords<ResultBean> records = consumer.poll(Duration.ofMillis(100));
|
||||||
|
@ -67,10 +70,10 @@ public class WsConsumerLoopFull {
|
||||||
|
|
||||||
} catch (SQLException ex) {
|
} catch (SQLException ex) {
|
||||||
// handle any errors, please refer to the JDBC specifications for detailed exceptions info
|
// handle any errors, please refer to the JDBC specifications for detailed exceptions info
|
||||||
System.out.println("Failed to poll data; ErrCode:" + ex.getErrorCode() + "; ErrMessage: " + ex.getMessage());
|
System.out.println("Failed to poll data, ErrCode:" + ex.getErrorCode() + "; ErrMessage: " + ex.getMessage());
|
||||||
throw new SQLException("Failed to poll data", ex);
|
throw new SQLException("Failed to poll data", ex);
|
||||||
} catch (Exception ex) {
|
} catch (Exception ex) {
|
||||||
System.out.println("Failed to poll data; ErrMessage: " + ex.getMessage());
|
System.out.println("Failed to poll data, ErrMessage: " + ex.getMessage());
|
||||||
throw new SQLException("Failed to poll data", ex);
|
throw new SQLException("Failed to poll data", ex);
|
||||||
}
|
}
|
||||||
// ANCHOR_END: poll_data_code_piece
|
// ANCHOR_END: poll_data_code_piece
|
||||||
|
@ -83,9 +86,9 @@ public class WsConsumerLoopFull {
|
||||||
|
|
||||||
// subscribe to the topics
|
// subscribe to the topics
|
||||||
consumer.subscribe(topics);
|
consumer.subscribe(topics);
|
||||||
System.out.println("subscribe topics successfully");
|
System.out.println("Subscribe topics successfully.");
|
||||||
Set<TopicPartition> assignment = consumer.assignment();
|
Set<TopicPartition> assignment = consumer.assignment();
|
||||||
System.out.println("now assignment: " + JSON.toJSONString(assignment));
|
System.out.println("Now assignment: " + JSON.toJSONString(assignment));
|
||||||
|
|
||||||
ConsumerRecords<ResultBean> records = ConsumerRecords.emptyRecord();
|
ConsumerRecords<ResultBean> records = ConsumerRecords.emptyRecord();
|
||||||
// make sure we have got some data
|
// make sure we have got some data
|
||||||
|
@ -94,14 +97,13 @@ public class WsConsumerLoopFull {
|
||||||
}
|
}
|
||||||
|
|
||||||
consumer.seekToBeginning(assignment);
|
consumer.seekToBeginning(assignment);
|
||||||
System.out.println("assignment seek to beginning successfully");
|
System.out.println("Assignment seek to beginning successfully.");
|
||||||
System.out.println("beginning assignment: " + JSON.toJSONString(assignment));
|
|
||||||
} catch (SQLException ex) {
|
} catch (SQLException ex) {
|
||||||
// handle any errors, please refer to the JDBC specifications for detailed exceptions info
|
// handle any errors, please refer to the JDBC specifications for detailed exceptions info
|
||||||
System.out.println("seek example failed; ErrCode:" + ex.getErrorCode() + "; ErrMessage: " + ex.getMessage());
|
System.out.println("Seek example failed; ErrCode:" + ex.getErrorCode() + "; ErrMessage: " + ex.getMessage());
|
||||||
throw new SQLException("seek example failed", ex);
|
throw new SQLException("seek example failed", ex);
|
||||||
} catch (Exception ex) {
|
} catch (Exception ex) {
|
||||||
System.out.println("seek example failed; ErrMessage: " + ex.getMessage());
|
System.out.println("Seek example failed; ErrMessage: " + ex.getMessage());
|
||||||
throw new SQLException("seek example failed", ex);
|
throw new SQLException("seek example failed", ex);
|
||||||
}
|
}
|
||||||
// ANCHOR_END: consumer_seek
|
// ANCHOR_END: consumer_seek
|
||||||
|
@ -124,6 +126,7 @@ public class WsConsumerLoopFull {
|
||||||
if (!records.isEmpty()) {
|
if (!records.isEmpty()) {
|
||||||
// after processing the data, commit the offset manually
|
// after processing the data, commit the offset manually
|
||||||
consumer.commitSync();
|
consumer.commitSync();
|
||||||
|
System.out.println("Commit offset manually successfully.");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch (SQLException ex) {
|
} catch (SQLException ex) {
|
||||||
|
@ -144,6 +147,7 @@ public class WsConsumerLoopFull {
|
||||||
try {
|
try {
|
||||||
// unsubscribe the consumer
|
// unsubscribe the consumer
|
||||||
consumer.unsubscribe();
|
consumer.unsubscribe();
|
||||||
|
System.out.println("Consumer unsubscribed successfully.");
|
||||||
} catch (SQLException ex) {
|
} catch (SQLException ex) {
|
||||||
// handle any errors, please refer to the JDBC specifications for detailed exceptions info
|
// handle any errors, please refer to the JDBC specifications for detailed exceptions info
|
||||||
System.out.println("Failed to unsubscribe consumer. ErrCode:" + ex.getErrorCode() + "; ErrMessage: " + ex.getMessage());
|
System.out.println("Failed to unsubscribe consumer. ErrCode:" + ex.getErrorCode() + "; ErrMessage: " + ex.getMessage());
|
||||||
|
@ -155,6 +159,7 @@ public class WsConsumerLoopFull {
|
||||||
finally {
|
finally {
|
||||||
// close the consumer
|
// close the consumer
|
||||||
consumer.close();
|
consumer.close();
|
||||||
|
System.out.println("Consumer closed successfully.");
|
||||||
}
|
}
|
||||||
// ANCHOR_END: unsubscribe_data_code_piece
|
// ANCHOR_END: unsubscribe_data_code_piece
|
||||||
}
|
}
|
||||||
|
@ -310,26 +315,26 @@ public class WsConsumerLoopFull {
|
||||||
System.out.println("Failed to prepare data, ErrMessage: " + ex.getMessage());
|
System.out.println("Failed to prepare data, ErrMessage: " + ex.getMessage());
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
System.out.println("pollDataExample executed successfully");
|
System.out.println("pollDataExample executed successfully.");
|
||||||
});
|
});
|
||||||
|
|
||||||
try {
|
try {
|
||||||
TaosConsumer<ResultBean> consumer = getConsumer();
|
TaosConsumer<ResultBean> consumer = getConsumer();
|
||||||
|
|
||||||
pollExample(consumer);
|
pollExample(consumer);
|
||||||
System.out.println("pollExample executed successfully");
|
System.out.println("pollExample executed successfully.");
|
||||||
consumer.unsubscribe();
|
consumer.unsubscribe();
|
||||||
|
|
||||||
seekExample(consumer);
|
seekExample(consumer);
|
||||||
System.out.println("seekExample executed successfully");
|
System.out.println("seekExample executed successfully.");
|
||||||
consumer.unsubscribe();
|
consumer.unsubscribe();
|
||||||
|
|
||||||
commitExample(consumer);
|
commitExample(consumer);
|
||||||
System.out.println("commitExample executed successfully");
|
System.out.println("commitExample executed successfully.");
|
||||||
consumer.unsubscribe();
|
consumer.unsubscribe();
|
||||||
|
|
||||||
unsubscribeExample(consumer);
|
unsubscribeExample(consumer);
|
||||||
System.out.println("unsubscribeExample executed successfully");
|
System.out.println("unsubscribeExample executed successfully.");
|
||||||
|
|
||||||
} catch (SQLException ex) {
|
} catch (SQLException ex) {
|
||||||
System.out.println("Failed to poll data from topic_meters, ErrCode:" + ex.getErrorCode() + "; ErrMessage: " + ex.getMessage());
|
System.out.println("Failed to poll data from topic_meters, ErrCode:" + ex.getErrorCode() + "; ErrMessage: " + ex.getMessage());
|
||||||
|
|
|
@ -2,6 +2,21 @@
|
||||||
|
|
||||||
set -e
|
set -e
|
||||||
|
|
||||||
|
check_transactions() {
|
||||||
|
for i in {1..30}
|
||||||
|
do
|
||||||
|
output=$(taos -s "show transactions;")
|
||||||
|
if [[ $output == *"Query OK, 0 row(s)"* ]]; then
|
||||||
|
echo "Success: No transactions are in progress."
|
||||||
|
return 0
|
||||||
|
fi
|
||||||
|
sleep 1
|
||||||
|
done
|
||||||
|
|
||||||
|
echo "Error: Transactions are still in progress after 30 attempts."
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
|
||||||
taosd >>/dev/null 2>&1 &
|
taosd >>/dev/null 2>&1 &
|
||||||
taosadapter >>/dev/null 2>&1 &
|
taosadapter >>/dev/null 2>&1 &
|
||||||
sleep 1
|
sleep 1
|
||||||
|
@ -19,60 +34,61 @@ taos -s "drop database if exists power"
|
||||||
go run ./sqlquery/main.go
|
go run ./sqlquery/main.go
|
||||||
|
|
||||||
taos -s "drop database if exists power"
|
taos -s "drop database if exists power"
|
||||||
sleep 1
|
check_transactions || exit 1
|
||||||
go run ./queryreqid/main.go
|
go run ./queryreqid/main.go
|
||||||
|
|
||||||
taos -s "drop database if exists power"
|
taos -s "drop database if exists power"
|
||||||
sleep 1
|
check_transactions || exit 1
|
||||||
go run ./stmt/native/main.go
|
go run ./stmt/native/main.go
|
||||||
|
|
||||||
taos -s "drop database if exists power"
|
taos -s "drop database if exists power"
|
||||||
sleep 1
|
check_transactions || exit 1
|
||||||
go run ./stmt/ws/main.go
|
go run ./stmt/ws/main.go
|
||||||
|
|
||||||
taos -s "drop database if exists power"
|
taos -s "drop database if exists power"
|
||||||
sleep 1
|
check_transactions || exit 1
|
||||||
|
sleep 3
|
||||||
go run ./schemaless/native/main.go
|
go run ./schemaless/native/main.go
|
||||||
|
|
||||||
taos -s "drop database if exists power"
|
taos -s "drop database if exists power"
|
||||||
sleep 1
|
check_transactions || exit 1
|
||||||
go run ./schemaless/ws/main.go
|
go run ./schemaless/ws/main.go
|
||||||
|
|
||||||
taos -s "drop topic if exists topic_meters"
|
taos -s "drop topic if exists topic_meters"
|
||||||
sleep 1
|
check_transactions || exit 1
|
||||||
taos -s "drop database if exists power"
|
taos -s "drop database if exists power"
|
||||||
sleep 1
|
check_transactions || exit 1
|
||||||
go run ./tmq/native/main.go
|
go run ./tmq/native/main.go
|
||||||
|
|
||||||
taos -s "drop topic if exists topic_meters"
|
taos -s "drop topic if exists topic_meters"
|
||||||
sleep 1
|
check_transactions || exit 1
|
||||||
taos -s "drop database if exists power"
|
taos -s "drop database if exists power"
|
||||||
sleep 1
|
check_transactions || exit 1
|
||||||
go run ./tmq/ws/main.go
|
go run ./tmq/ws/main.go
|
||||||
|
|
||||||
|
|
||||||
taos -s "drop database if exists test"
|
taos -s "drop database if exists test"
|
||||||
sleep 1
|
check_transactions || exit 1
|
||||||
go run ./insert/json/main.go
|
go run ./insert/json/main.go
|
||||||
taos -s "drop database if exists test"
|
taos -s "drop database if exists test"
|
||||||
sleep 1
|
check_transactions || exit 1
|
||||||
go run ./insert/line/main.go
|
go run ./insert/line/main.go
|
||||||
taos -s "drop topic if exists topic_meters"
|
taos -s "drop topic if exists topic_meters"
|
||||||
sleep 1
|
check_transactions || exit 1
|
||||||
taos -s "drop database if exists power"
|
taos -s "drop database if exists power"
|
||||||
sleep 1
|
check_transactions || exit 1
|
||||||
go run ./insert/sql/main.go
|
go run ./insert/sql/main.go
|
||||||
taos -s "drop database if exists power"
|
taos -s "drop database if exists power"
|
||||||
sleep 1
|
check_transactions || exit 1
|
||||||
go run ./insert/stmt/main.go
|
go run ./insert/stmt/main.go
|
||||||
taos -s "drop database if exists test"
|
taos -s "drop database if exists test"
|
||||||
sleep 1
|
check_transactions || exit 1
|
||||||
go run ./insert/telnet/main.go
|
go run ./insert/telnet/main.go
|
||||||
|
|
||||||
go run ./query/sync/main.go
|
go run ./query/sync/main.go
|
||||||
|
|
||||||
taos -s "drop topic if exists example_tmq_topic"
|
taos -s "drop topic if exists example_tmq_topic"
|
||||||
sleep 1
|
check_transactions || exit 1
|
||||||
taos -s "drop database if exists example_tmq"
|
taos -s "drop database if exists example_tmq"
|
||||||
sleep 1
|
check_transactions || exit 1
|
||||||
go run ./sub/main.go
|
go run ./sub/main.go
|
||||||
|
|
Loading…
Reference in New Issue