高效写入
本节介绍如何高效地向 TDengine 写入数据。
高效写入原理
客户端程序的角度
从客户端程序的角度来说,高效写入数据要考虑以下几个因素:
- 单次写入的数据量。一般来讲,每批次写入的数据量越大越高效(但超过一定阈值其优势会消失)。使用 SQL 写入 TDengine 时,尽量在一条 SQL 中拼接更多数据。目前,TDengine 支持的一条 SQL 的最大长度为 1,048,576(1MB)个字符
- 并发连接数。一般来讲,同时写入数据的并发连接数越多写入越高效(但超过一定阈值反而会下降,取决于服务端处理能力)
- 数据在不同表(或子表)之间的分布,即要写入数据的相邻性。一般来说,每批次只向同一张表(或子表)写入数据比向多张表(或子表)写入数据要更高效
- 写入方式。一般来讲:
- 参数绑定写入比 SQL 写入更高效。因参数绑定方式避免了 SQL 解析。(但增加了 C 接口的调用次数,对于连接器也有性能损耗)
- SQL 写入不自动建表比自动建表更高效。因自动建表要频繁检查表是否存在
- SQL 写入比无模式写入更高效。因无模式写入会自动建表且支持动态更改表结构
客户端程序要充分且恰当地利用以上几个因素。在单次写入中尽量只向同一张表(或子表)写入数据,每批次写入的数据量经过测试和调优设定为一个最适合当前系统处理能力的数值,并发写入的连接数同样经过测试和调优后设定为一个最适合当前系统处理能力的数值,以实现在当前系统中的最佳写入速度。
数据源的角度
客户端程序通常需要从数据源读数据再写入 TDengine。从数据源角度来说,以下几种情况需要在读线程和写线程之间增加队列:
- 有多个数据源,单个数据源生成数据的速度远小于单线程写入的速度,但数据量整体比较大。此时队列的作用是把多个数据源的数据汇聚到一起,增加单次写入的数据量。
- 单个数据源生成数据的速度远大于单线程写入的速度。此时队列的作用是增加写入的并发度。
- 单张表的数据分散在多个数据源。此时队列的作用是将同一张表的数据提前汇聚到一起,提高写入时数据的相邻性。
如果写应用的数据源是 Kafka, 写应用本身即 Kafka 的消费者,则可利用 Kafka 的特性实现高效写入。比如:
- 将同一张表的数据写到同一个 Topic 的同一个 Partition,增加数据的相邻性
- 通过订阅多个 Topic 实现数据汇聚
- 通过增加 Consumer 线程数增加写入的并发度
- 通过增加每次 Fetch 的最大数据量来增加单次写入的最大数据量
服务器配置的角度
从服务端配置的角度,要根据系统中磁盘的数量,磁盘的 I/O 能力,以及处理器能力在创建数据库时设置适当的 vgroups 数量以充分发挥系统性能。如果 vgroups 过少,则系统性能无法发挥;如果 vgroups 过多,会造成无谓的资源竞争。常规推荐 vgroups 数量为 CPU 核数的 2 倍,但仍然要结合具体的系统资源配置进行调优。
高效写入示例
场景设计
下面的示例程序展示了如何高效写入数据,场景设计如下:
- TDengine 客户端程序从其它数据源不断读入数据,在示例程序中采用生成模拟数据的方式来模拟读取数据源
- 单个连接向 TDengine 写入的速度无法与读数据的速度相匹配,因此客户端程序启动多个线程,每个线程都建立了与 TDengine 的连接,每个线程都有一个独占的固定大小的消息队列
- 客户端程序将接收到的数据根据所属的表名(或子表名)HASH 到不同的线程,即写入该线程所对应的消息队列,以此确保属于某个表(或子表)的数据一定会被一个固定的线程处理
- 各个子线程在将所关联的消息队列中的数据读空后或者读取数据量达到一个预定的阈值后将该批数据写入 TDengine,并继续处理后面接收到的数据

示例代码
这一部分是针对以上场景的示例代码。对于其它场景高效写入原理相同,不过代码需要适当修改。
本示例代码假设源数据属于同一张超级表(meters)的不同子表。程序在开始写入数据之前已经在 test 库创建了这个超级表。对于子表,将根据收到的数据,由应用程序自动创建。如果实际场景是多个超级表,只需修改写任务自动建表的代码。
- Java
- Python
程序清单
| 类名 | 功能说明 |
|---|---|
| FastWriteExample | 主程序 |
| ReadTask | 从模拟源中读取数据,将表名经过 Hash 后得到 Queue 的 Index,写入对应的 Queue |
| WriteTask | 从 Queue 中获取数据,组成一个 Batch,写入 TDengine |
| MockDataSource | 模拟生成一定数量 meters 子表的数据 |
| SQLWriter | WriteTask 依赖这个类完成 SQL 拼接、自动建表、 SQL 写入、SQL 长度检查 |
| StmtWriter | 实现参数绑定方式批量写入(暂未完成) |
| DataBaseMonitor | 统计写入速度,并每隔 10 秒把当前写入速度打印到控制台 |
以下是各类的完整代码和更详细的功能说明。
FastWriteExample
主程序负责:
- 创建消息队列
- 启动写线程
- 启动读线程
- 每隔 10 秒统计一次写入速度
主程序默认暴露了 4 个参数,每次启动程序都可调节,用于测试和调优:
- 读线程个数。默认为 1。
- 写线程个数。默认为 3。
- 模拟生成的总表数。默认为 1,000。将会平分给各个读线程。如果总表数较大,建表需要花费较长,开始统计的写入速度可能较慢。
- 每批最多写入记录数量。默认为 3,000。
队列容量(taskQueueCapacity)也是与性能有关的参数,可通过修改程序调节。一般来讲,队列容量越大,入队被阻塞的概率越小,队列的吞吐量越大,但是内存占用也会越大。示例程序默认值已经设置地足够大。
1. package com.taos.example.highvolume;
3. import org.slf4j.Logger;
4. import org.slf4j.LoggerFactory;
6. import java.sql.*;
7. import java.util.ArrayList;
8. import java.util.List;
9. import java.util.concurrent.ArrayBlockingQueue;
10. import java.util.concurrent.BlockingQueue;
13. public class FastWriteExample {
14. final static Logger logger = LoggerFactory.getLogger(FastWriteExample.class);
16. final static int taskQueueCapacity = 1000000;
17. final static List<BlockingQueue<String>> taskQueues = new ArrayList<>();
18. final static List<ReadTask> readTasks = new ArrayList<>();
19. final static List<WriteTask> writeTasks = new ArrayList<>();
20. final static DataBaseMonitor databaseMonitor = new DataBaseMonitor();
22. public static void stopAll() {
23. logger.info("shutting down");
24. readTasks.forEach(task -> task.stop());
25. writeTasks.forEach(task -> task.stop());
26. databaseMonitor.close();
27. }
29. public static void main(String[] args) throws InterruptedException, SQLException {
30. int readTaskCount = args.length > 0 ? Integer.parseInt(args[0]) : 1;
31. int writeTaskCount = args.length > 1 ? Integer.parseInt(args[1]) : 3;
32. int tableCount = args.length > 2 ? Integer.parseInt(args[2]) : 1000;
33. int maxBatchSize = args.length > 3 ? Integer.parseInt(args[3]) : 3000;
35. logger.info("readTaskCount={}, writeTaskCount={} tableCount={} maxBatchSize={}",
36. readTaskCount, writeTaskCount, tableCount, maxBatchSize);
38. databaseMonitor.init().prepareDatabase();
40. // Create task queues, whiting tasks and start writing threads.
41. for (int i = 0; i < writeTaskCount; ++i) {
42. BlockingQueue<String> queue = new ArrayBlockingQueue<>(taskQueueCapacity);
43. taskQueues.add(queue);
44. WriteTask task = new WriteTask(queue, maxBatchSize);
45. Thread t = new Thread(task);
46. t.setName("WriteThread-" + i);
47. t.start();
48. }
50. // create reading tasks and start reading threads
51. int tableCountPerTask = tableCount / readTaskCount;
52. for (int i = 0; i < readTaskCount; ++i) {
53. ReadTask task = new ReadTask(i, taskQueues, tableCountPerTask);
54. Thread t = new Thread(task);
55. t.setName("ReadThread-" + i);
56. t.start();
57. }
59. Runtime.getRuntime().addShutdownHook(new Thread(FastWriteExample::stopAll));
61. long lastCount = 0;
62. while (true) {
63. Thread.sleep(10000);
64. long numberOfTable = databaseMonitor.getTableCount();
65. long count = databaseMonitor.count();
66. logger.info("numberOfTable={} count={} speed={}", numberOfTable, count, (count - lastCount) / 10);
67. lastCount = count;
68. }
69. }
70. }
ReadTask
读任务负责从数据源读数据。每个读任务都关联了一个模拟数据源。每个模拟数据源可生成一点数量表的数据。不同的模拟数据源生成不同表的数据。
读任务采用阻塞的方式写消息队列。也就是说,一旦队列满了,写操作就会阻塞。
1. package com.taos.example.highvolume;
3. import org.slf4j.Logger;
4. import org.slf4j.LoggerFactory;
6. import java.util.Iterator;
7. import java.util.List;
8. import java.util.concurrent.BlockingQueue;
10. class ReadTask implements Runnable {
11. private final static Logger logger = LoggerFactory.getLogger(ReadTask.class);
12. private final int taskId;
13. private final List<BlockingQueue<String>> taskQueues;
14. private final int queueCount;
15. private final int tableCount;
16. private boolean active = true;
18. public ReadTask(int readTaskId, List<BlockingQueue<String>> queues, int tableCount) {
19. this.taskId = readTaskId;
20. this.taskQueues = queues;
21. this.queueCount = queues.size();
22. this.tableCount = tableCount;
23. }
25. /**
26. * Assign data received to different queues.
27. * Here we use the suffix number in table name.
28. * You are expected to define your own rule in practice.
29. *
30. * @param line record received
31. * @return which queue to use
32. */
33. public int getQueueId(String line) {
34. String tbName = line.substring(0, line.indexOf(',')); // For example: tb1_101
35. String suffixNumber = tbName.split("_")[1];
36. return Integer.parseInt(suffixNumber) % this.queueCount;
37. }
39. @Override
40. public void run() {
41. logger.info("started");
42. Iterator<String> it = new MockDataSource("tb" + this.taskId, tableCount);
43. try {
44. while (it.hasNext() && active) {
45. String line = it.next();
46. int queueId = getQueueId(line);
47. taskQueues.get(queueId).put(line);
48. }
49. } catch (Exception e) {
50. logger.error("Read Task Error", e);
51. }
52. }
54. public void stop() {
55. logger.info("stop");
56. this.active = false;
57. }
58. }
WriteTask
1. package com.taos.example.highvolume;
3. import org.slf4j.Logger;
4. import org.slf4j.LoggerFactory;
6. import java.util.concurrent.BlockingQueue;
8. class WriteTask implements Runnable {
9. private final static Logger logger = LoggerFactory.getLogger(WriteTask.class);
10. private final int maxBatchSize;
12. // the queue from which this writing task get raw data.
13. private final BlockingQueue<String> queue;
15. // A flag indicate whether to continue.
16. private boolean active = true;
18. public WriteTask(BlockingQueue<String> taskQueue, int maxBatchSize) {
19. this.queue = taskQueue;
20. this.maxBatchSize = maxBatchSize;
21. }
23. @Override
24. public void run() {
25. logger.info("started");
26. String line = null; // data getting from the queue just now.
27. SQLWriter writer = new SQLWriter(maxBatchSize);
28. try {
29. writer.init();
30. while (active) {
31. line = queue.poll();
32. if (line != null) {
33. // parse raw data and buffer the data.
34. writer.processLine(line);
35. } else if (writer.hasBufferedValues()) {
36. // write data immediately if no more data in the queue
37. writer.flush();
38. } else {
39. // sleep a while to avoid high CPU usage if no more data in the queue and no buffered records, .
40. Thread.sleep(100);
41. }
42. }
43. if (writer.hasBufferedValues()) {
44. writer.flush();
45. }
46. } catch (Exception e) {
47. String msg = String.format("line=%s, bufferedCount=%s", line, writer.getBufferedCount());
48. logger.error(msg, e);
49. } finally {
50. writer.close();
51. }
52. }
54. public void stop() {
55. logger.info("stop");
56. this.active = false;
57. }
58. }
MockDataSource
1. package com.taos.example.highvolume;
3. import java.util.Iterator;
5. /**
6. * Generate test data
7. */
8. class MockDataSource implements Iterator {
9. private String tbNamePrefix;
10. private int tableCount;
11. private long maxRowsPerTable = 1000000000L;
13. // 100 milliseconds between two neighbouring rows.
14. long startMs = System.currentTimeMillis() - maxRowsPerTable * 100;
15. private int currentRow = 0;
16. private int currentTbId = -1;
18. // mock values
19. String[] location = {"California.LosAngeles", "California.SanDiego", "California.SanJose", "California.Campbell", "California.SanFrancisco"};
20. float[] current = {8.8f, 10.7f, 9.9f, 8.9f, 9.4f};
21. int[] voltage = {119, 116, 111, 113, 118};
22. float[] phase = {0.32f, 0.34f, 0.33f, 0.329f, 0.141f};
24. public MockDataSource(String tbNamePrefix, int tableCount) {
25. this.tbNamePrefix = tbNamePrefix;
26. this.tableCount = tableCount;
27. }
29. @Override
30. public boolean hasNext() {
31. currentTbId += 1;
32. if (currentTbId == tableCount) {
33. currentTbId = 0;
34. currentRow += 1;
35. }
36. return currentRow < maxRowsPerTable;
37. }
39. @Override
40. public String next() {
41. long ts = startMs + 100 * currentRow;
42. int groupId = currentTbId % 5 == 0 ? currentTbId / 5 : currentTbId / 5 + 1;
43. StringBuilder sb = new StringBuilder(tbNamePrefix + "_" + currentTbId + ","); // tbName
44. sb.append(ts).append(','); // ts
45. sb.append(current[currentRow % 5]).append(','); // current
46. sb.append(voltage[currentRow % 5]).append(','); // voltage
47. sb.append(phase[currentRow % 5]).append(','); // phase
48. sb.append(location[currentRow % 5]).append(','); // location
49. sb.append(groupId); // groupID
51. return sb.toString();
52. }
53. }
SQLWriter
SQLWriter 类封装了拼 SQL 和写数据的逻辑。注意,所有的表都没有提前创建,而是在 catch 到表不存在异常的时候,再以超级表为模板批量建表,然后重新执行 INSERT 语句。对于其它异常,这里简单地记录当时执行的 SQL 语句到日志中,你也可以记录更多线索到日志,已便排查错误和故障恢复。
1. package com.taos.example.highvolume;
3. import org.slf4j.Logger;
4. import org.slf4j.LoggerFactory;
6. import java.sql.*;
7. import java.util.HashMap;
8. import java.util.Map;
10. /**
11. * A helper class encapsulate the logic of writing using SQL.
12. * <p>
13. * The main interfaces are two methods:
14. * <ol>
15. * <li>{@link SQLWriter#processLine}, which receive raw lines from WriteTask and group them by table names.</li>
16. * <li>{@link SQLWriter#flush}, which assemble INSERT statement and execute it.</li>
17. * </ol>
18. * <p>
19. * There is a technical skill worth mentioning: we create table as needed when "table does not exist" error occur instead of creating table automatically using syntax "INSET INTO tb USING stb".
20. * This ensure that checking table existence is a one-time-only operation.
21. * </p>
22. *
23. * </p>
24. */
25. public class SQLWriter {
26. final static Logger logger = LoggerFactory.getLogger(SQLWriter.class);
28. private Connection conn;
29. private Statement stmt;
31. /**
32. * current number of buffered records
33. */
34. private int bufferedCount = 0;
35. /**
36. * Maximum number of buffered records.
37. * Flush action will be triggered if bufferedCount reached this value,
38. */
39. private int maxBatchSize;
42. /**
43. * Maximum SQL length.
44. */
45. private int maxSQLLength = 800_000;
47. /**
48. * Map from table name to column values. For example:
49. * "tb001" -> "(1648432611249,2.1,114,0.09) (1648432611250,2.2,135,0.2)"
50. */
51. private Map<String, String> tbValues = new HashMap<>();
53. /**
54. * Map from table name to tag values in the same order as creating stable.
55. * Used for creating table.
56. */
57. private Map<String, String> tbTags = new HashMap<>();
59. public SQLWriter(int maxBatchSize) {
60. this.maxBatchSize = maxBatchSize;
61. }
64. /**
65. * Get Database Connection
66. *
67. * @return Connection
68. * @throws SQLException
69. */
70. private static Connection getConnection() throws SQLException {
71. String jdbcURL = System.getenv("TDENGINE_JDBC_URL");
72. return DriverManager.getConnection(jdbcURL);
73. }
75. /**
76. * Create Connection and Statement
77. *
78. * @throws SQLException
79. */
80. public void init() throws SQLException {
81. conn = getConnection();
82. stmt = conn.createStatement();
83. stmt.execute("use test");
84. }
86. /**
87. * Convert raw data to SQL fragments, group them by table name and cache them in a HashMap.
88. * Trigger writing when number of buffered records reached maxBachSize.
89. *
90. * @param line raw data get from task queue in format: tbName,ts,current,voltage,phase,location,groupId
91. */
92. public void processLine(String line) throws SQLException {
93. bufferedCount += 1;
94. int firstComma = line.indexOf(',');
95. String tbName = line.substring(0, firstComma);
96. int lastComma = line.lastIndexOf(',');
97. int secondLastComma = line.lastIndexOf(',', lastComma - 1);
98. String value = "(" + line.substring(firstComma + 1, secondLastComma) + ") ";
99. if (tbValues.containsKey(tbName)) {
100. tbValues.put(tbName, tbValues.get(tbName) + value);
101. } else {
102. tbValues.put(tbName, value);
103. }
104. if (!tbTags.containsKey(tbName)) {
105. String location = line.substring(secondLastComma + 1, lastComma);
106. String groupId = line.substring(lastComma + 1);
107. String tagValues = "('" + location + "'," + groupId + ')';
108. tbTags.put(tbName, tagValues);
109. }
110. if (bufferedCount == maxBatchSize) {
111. flush();
112. }
113. }
116. /**
117. * Assemble INSERT statement using buffered SQL fragments in Map {@link SQLWriter#tbValues} and execute it.
118. * In case of "Table does not exit" exception, create all tables in the sql and retry the sql.
119. */
120. public void flush() throws SQLException {
121. StringBuilder sb = new StringBuilder("INSERT INTO ");
122. for (Map.Entry<String, String> entry : tbValues.entrySet()) {
123. String tableName = entry.getKey();
124. String values = entry.getValue();
125. String q = tableName + " values " + values + " ";
126. if (sb.length() + q.length() > maxSQLLength) {
127. executeSQL(sb.toString());
128. logger.warn("increase maxSQLLength or decrease maxBatchSize to gain better performance");
129. sb = new StringBuilder("INSERT INTO ");
130. }
131. sb.append(q);
132. }
133. executeSQL(sb.toString());
134. tbValues.clear();
135. bufferedCount = 0;
136. }
138. private void executeSQL(String sql) throws SQLException {
139. try {
140. stmt.executeUpdate(sql);
141. } catch (SQLException e) {
142. // convert to error code defined in taoserror.h
143. int errorCode = e.getErrorCode() & 0xffff;
144. if (errorCode == 0x2603) {
145. // Table does not exist
146. createTables();
147. executeSQL(sql);
148. } else {
149. logger.error("Execute SQL: {}", sql);
150. throw e;
151. }
152. } catch (Throwable throwable) {
153. logger.error("Execute SQL: {}", sql);
154. throw throwable;
155. }
156. }
158. /**
159. * Create tables in batch using syntax:
160. * <p>
161. * CREATE TABLE [IF NOT EXISTS] tb_name1 USING stb_name TAGS (tag_value1, ...) [IF NOT EXISTS] tb_name2 USING stb_name TAGS (tag_value2, ...) ...;
162. * </p>
163. */
164. private void createTables() throws SQLException {
165. StringBuilder sb = new StringBuilder("CREATE TABLE ");
166. for (String tbName : tbValues.keySet()) {
167. String tagValues = tbTags.get(tbName);
168. sb.append("IF NOT EXISTS ").append(tbName).append(" USING meters TAGS ").append(tagValues).append(" ");
169. }
170. String sql = sb.toString();
171. try {
172. stmt.executeUpdate(sql);
173. } catch (Throwable throwable) {
174. logger.error("Execute SQL: {}", sql);
175. throw throwable;
176. }
177. }
179. public boolean hasBufferedValues() {
180. return bufferedCount > 0;
181. }
183. public int getBufferedCount() {
184. return bufferedCount;
185. }
187. public void close() {
188. try {
189. stmt.close();
190. } catch (SQLException e) {
191. }
192. try {
193. conn.close();
194. } catch (SQLException e) {
195. }
196. }
197. }
DataBaseMonitor
1. package com.taos.example.highvolume;
3. import java.sql.*;
5. /**
6. * Prepare target database.
7. * Count total records in database periodically so that we can estimate the writing speed.
8. */
9. public class DataBaseMonitor {
10. private Connection conn;
11. private Statement stmt;
13. public DataBaseMonitor init() throws SQLException {
14. if (conn == null) {
15. String jdbcURL = System.getenv("TDENGINE_JDBC_URL");
16. conn = DriverManager.getConnection(jdbcURL);
17. stmt = conn.createStatement();
18. }
19. return this;
20. }
22. public void close() {
23. try {
24. stmt.close();
25. } catch (SQLException e) {
26. }
27. try {
28. conn.close();
29. } catch (SQLException e) {
30. }
31. }
33. public void prepareDatabase() throws SQLException {
34. stmt.execute("DROP DATABASE IF EXISTS test");
35. stmt.execute("CREATE DATABASE test");
36. stmt.execute("CREATE STABLE test.meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (location BINARY(64), groupId INT)");
37. }
39. public long count() throws SQLException {
40. try (ResultSet result = stmt.executeQuery("SELECT count(*) from test.meters")) {
41. result.next();
42. return result.getLong(1);
43. }
44. }
46. public long getTableCount() throws SQLException {
47. try (ResultSet result = stmt.executeQuery("select count(*) from information_schema.ins_tables where db_name = 'test';")) {
48. result.next();
49. return result.getLong(1);
50. }
51. }
52. }
执行步骤
执行 Java 示例程序
执行程序前需配置环境变量 TDENGINE_JDBC_URL。如果 TDengine Server 部署在本机,且用户名、密码和端口都是默认值,那么可配置:
1. TDENGINE_JDBC_URL="jdbc:TAOS://localhost:6030?user=root&password=taosdata"
本地集成开发环境执行示例程序
- clone TDengine 仓库
1. git clone git@github.com:taosdata/TDengine.git --depth 1
2. 用集成开发环境打开 docs/examples/java 目录。
3. 在开发环境中配置环境变量 TDENGINE_JDBC_URL。如果已配置了全局的环境变量 TDENGINE_JDBC_URL 可跳过这一步。
4. 运行类 com.taos.example.highvolume.FastWriteExample。
远程服务器上执行示例程序
若要在服务器上执行示例程序,可按照下面的步骤操作:
- 打包示例代码。在目录 TDengine/docs/examples/java 下执行:
1. mvn package
2. 远程服务器上创建 examples 目录:
1. mkdir -p examples/java
3. 复制依赖到服务器指定目录:
-
复制依赖包,只用复制一次
1. scp -r .\target\lib <user>@<host>:~/examples/java- 复制本程序的 jar 包,每次更新代码都需要复制1. scp -r .\target\javaexample-1.0.jar <user>@<host>:~/examples/java4. 配置环境变量。 编辑~/.bash_profile或~/.bashrc添加如下内容例如:
1. export TDENGINE_JDBC_URL="jdbc:TAOS://localhost:6030?user=root&password=taosdata"
以上使用的是本地部署 TDengine Server 时默认的 JDBC URL。你需要根据自己的实际情况更改。 5. 用 Java 命令启动示例程序,命令模板:
1. java -classpath lib/*:javaexample-1.0.jar com.taos.example.highvolume.FastWriteExample <read_thread_count> <white_thread_count> <total_table_count> <max_batch_size>
6. 结束测试程序。测试程序不会自动结束,在获取到当前配置下稳定的写入速度后,按 CTRL + C 结束程序。 下面是一次实际运行的日志输出,机器配置 16 核 + 64G + 固态硬盘。
1. root@vm85$ java -classpath lib/*:javaexample-1.0.jar com.taos.example.highvolume.FastWriteExample 2 12
2. 18:56:35.896 [main] INFO c.t.e.highvolume.FastWriteExample - readTaskCount=2, writeTaskCount=12 tableCount=1000 maxBatchSize=3000
3. 18:56:36.011 [WriteThread-0] INFO c.taos.example.highvolume.WriteTask - started
4. 18:56:36.015 [WriteThread-0] INFO c.taos.example.highvolume.SQLWriter - maxSQLLength=1048576
5. 18:56:36.021 [WriteThread-1] INFO c.taos.example.highvolume.WriteTask - started
6. 18:56:36.022 [WriteThread-1] INFO c.taos.example.highvolume.SQLWriter - maxSQLLength=1048576
7. 18:56:36.031 [WriteThread-2] INFO c.taos.example.highvolume.WriteTask - started
8. 18:56:36.032 [WriteThread-2] INFO c.taos.example.highvolume.SQLWriter - maxSQLLength=1048576
9. 18:56:36.041 [WriteThread-3] INFO c.taos.example.highvolume.WriteTask - started
10. 18:56:36.042 [WriteThread-3] INFO c.taos.example.highvolume.SQLWriter - maxSQLLength=1048576
11. 18:56:36.093 [WriteThread-4] INFO c.taos.example.highvolume.WriteTask - started
12. 18:56:36.094 [WriteThread-4] INFO c.taos.example.highvolume.SQLWriter - maxSQLLength=1048576
13. 18:56:36.099 [WriteThread-5] INFO c.taos.example.highvolume.WriteTask - started
14. 18:56:36.100 [WriteThread-5] INFO c.taos.example.highvolume.SQLWriter - maxSQLLength=1048576
15. 18:56:36.100 [WriteThread-6] INFO c.taos.example.highvolume.WriteTask - started
16. 18:56:36.101 [WriteThread-6] INFO c.taos.example.highvolume.SQLWriter - maxSQLLength=1048576
17. 18:56:36.103 [WriteThread-7] INFO c.taos.example.highvolume.WriteTask - started
18. 18:56:36.104 [WriteThread-7] INFO c.taos.example.highvolume.SQLWriter - maxSQLLength=1048576
19. 18:56:36.105 [WriteThread-8] INFO c.taos.example.highvolume.WriteTask - started
20. 18:56:36.107 [WriteThread-8] INFO c.taos.example.highvolume.SQLWriter - maxSQLLength=1048576
21. 18:56:36.108 [WriteThread-9] INFO c.taos.example.highvolume.WriteTask - started
22. 18:56:36.109 [WriteThread-9] INFO c.taos.example.highvolume.SQLWriter - maxSQLLength=1048576
23. 18:56:36.156 [WriteThread-10] INFO c.taos.example.highvolume.WriteTask - started
24. 18:56:36.157 [WriteThread-11] INFO c.taos.example.highvolume.WriteTask - started
25. 18:56:36.158 [WriteThread-10] INFO c.taos.example.highvolume.SQLWriter - maxSQLLength=1048576
26. 18:56:36.158 [ReadThread-0] INFO com.taos.example.highvolume.ReadTask - started
27. 18:56:36.158 [ReadThread-1] INFO com.taos.example.highvolume.ReadTask - started
28. 18:56:36.158 [WriteThread-11] INFO c.taos.example.highvolume.SQLWriter - maxSQLLength=1048576
29. 18:56:46.369 [main] INFO c.t.e.highvolume.FastWriteExample - count=18554448 speed=1855444
30. 18:56:56.946 [main] INFO c.t.e.highvolume.FastWriteExample - count=39059660 speed=2050521
31. 18:57:07.322 [main] INFO c.t.e.highvolume.FastWriteExample - count=59403604 speed=2034394
32. 18:57:18.032 [main] INFO c.t.e.highvolume.FastWriteExample - count=80262938 speed=2085933
33. 18:57:28.432 [main] INFO c.t.e.highvolume.FastWriteExample - count=101139906 speed=2087696
34. 18:57:38.921 [main] INFO c.t.e.highvolume.FastWriteExample - count=121807202 speed=2066729
35. 18:57:49.375 [main] INFO c.t.e.highvolume.FastWriteExample - count=142952417 speed=2114521
36. 18:58:00.689 [main] INFO c.t.e.highvolume.FastWriteExample - count=163650306 speed=2069788
37. 18:58:11.646 [main] INFO c.t.e.highvolume.FastWriteExample - count=185019808 speed=2136950
程序清单
Python 示例程序中采用了多进程的架构,并使用了跨进程的消息队列。
| 函数或类 | 功能说明 |
|---|---|
| main 函数 | 程序入口, 创建各个子进程和消息队列 |
| run_monitor_process 函数 | 创建数据库,超级表,统计写入速度并定时打印到控制台 |
| run_read_task 函数 | 读进程主要逻辑,负责从其它数据系统读数据,并分发数据到为之分配的队列 |
| MockDataSource 类 | 模拟数据源, 实现迭代器接口,每次批量返回每张表的接下来 1,000 条数据 |
| run_write_task 函数 | 写进程主要逻辑。每次从队列中取出尽量多的数据,并批量写入 |
| SQLWriter 类 | SQL 写入和自动建表 |
| StmtWriter 类 | 实现参数绑定方式批量写入(暂未完成) |
main 函数
main 函数负责创建消息队列和启动子进程,子进程有 3 类:
- 1 个监控进程,负责数据库初始化和统计写入速度
- n 个读进程,负责从其它数据系统读数据
- m 个写进程,负责写数据库
main 函数可以接收 5 个启动参数,依次是:
- 读任务(进程)数, 默认为 1
- 写任务(进程)数, 默认为 1
- 模拟生成的总表数,默认为 1,000
- 队列大小(单位字节),默认为 1,000,000
- 每批最多写入记录数量, 默认为 3,000
1. def main(infinity):
2. set_global_config()
3. logging.info(f"READ_TASK_COUNT={READ_TASK_COUNT}, WRITE_TASK_COUNT={WRITE_TASK_COUNT}, "
4. f"TABLE_COUNT={TABLE_COUNT}, QUEUE_SIZE={QUEUE_SIZE}, MAX_BATCH_SIZE={MAX_BATCH_SIZE}")
6. conn = get_connection()
7. conn.execute("DROP DATABASE IF EXISTS test")
8. conn.execute("CREATE DATABASE IF NOT EXISTS test")
9. conn.execute("CREATE STABLE IF NOT EXISTS test.meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) "
10. "TAGS (location BINARY(64), groupId INT)")
11. conn.close()
13. done_queue = Queue()
14. monitor_process = Process(target=run_monitor_process, args=(done_queue,))
15. monitor_process.start()
16. logging.debug(f"monitor task started with pid {monitor_process.pid}")
18. task_queues: List[Queue] = []
19. write_processes = []
20. read_processes = []
22. # create task queues
23. for i in range(WRITE_TASK_COUNT):
24. queue = Queue()
25. task_queues.append(queue)
27. # create write processes
28. for i in range(WRITE_TASK_COUNT):
29. p = Process(target=run_write_task, args=(i, task_queues[i], done_queue))
30. p.start()
31. logging.debug(f"WriteTask-{i} started with pid {p.pid}")
32. write_processes.append(p)
34. # create read processes
35. for i in range(READ_TASK_COUNT):
36. queues = assign_queues(i, task_queues)
37. p = Process(target=run_read_task, args=(i, queues, infinity))
38. p.start()
39. logging.debug(f"ReadTask-{i} started with pid {p.pid}")
40. read_processes.append(p)
42. try:
43. monitor_process.join()
44. for p in read_processes:
45. p.join()
46. for p in write_processes:
47. p.join()
48. time.sleep(1)
49. return
50. except KeyboardInterrupt:
51. monitor_process.terminate()
52. [p.terminate() for p in read_processes]
53. [p.terminate() for p in write_processes]
54. [q.close() for q in task_queues]
57. def assign_queues(read_task_id, task_queues):
58. """
59. Compute target queues for a specific read task.
60. """
61. ratio = WRITE_TASK_COUNT / READ_TASK_COUNT
62. from_index = math.floor(read_task_id * ratio)
63. end_index = math.ceil((read_task_id + 1) * ratio)
64. return task_queues[from_index:end_index]
67. if __name__ == '__main__':
68. multiprocessing.set_start_method('spawn')
69. main(False)
run_monitor_process
监控进程负责初始化数据库,并监控当前的写入速度。
1. def run_monitor_process(done_queue: Queue):
2. log = logging.getLogger("DataBaseMonitor")
3. conn = None
4. try:
5. conn = get_connection()
7. def get_count():
8. res = conn.query("SELECT count(*) FROM test.meters")
9. rows = res.fetch_all()
10. return rows[0][0] if rows else 0
12. last_count = 0
13. while True:
14. try:
15. done = done_queue.get_nowait()
16. if done == _DONE_MESSAGE:
17. break
18. except Empty:
19. pass
20. time.sleep(10)
21. count = get_count()
22. log.info(f"count={count} speed={(count - last_count) / 10}")
23. last_count = count
24. finally:
25. conn.close()
run_read_task 函数
读进程,负责从其它数据系统读数据,并分发数据到为之分配的队列。
2. def run_read_task(task_id: int, task_queues: List[Queue], infinity):
3. table_count_per_task = TABLE_COUNT // READ_TASK_COUNT
4. data_source = MockDataSource(f"tb{task_id}", table_count_per_task, infinity)
5. try:
6. for batch in data_source:
7. if isinstance(batch, tuple):
8. batch = [batch]
9. for table_id, rows in batch:
10. # hash data to different queue
11. i = table_id % len(task_queues)
12. # block putting forever when the queue is full
13. for row in rows:
14. task_queues[i].put(row)
15. if not infinity:
16. for queue in task_queues:
17. queue.put(_DONE_MESSAGE)
18. except KeyboardInterrupt:
19. pass
20. finally:
21. logging.info('read task over')
MockDataSource
以下是模拟数据源的实现,我们假设数据源生成的每一条数据都带有目标表名信息。实际中你可能需要一定的规则确定目标表名。
1. import time
4. class MockDataSource:
5. samples = [
6. "8.8,119,0.32,California.LosAngeles,0",
7. "10.7,116,0.34,California.SanDiego,1",
8. "9.9,111,0.33,California.SanJose,2",
9. "8.9,113,0.329,California.Campbell,3",
10. "9.4,118,0.141,California.SanFrancisco,4"
11. ]
13. def __init__(self, tb_name_prefix, table_count, infinity=True):
14. self.table_name_prefix = tb_name_prefix + "_"
15. self.table_count = table_count
16. self.max_rows = 10000000
17. self.current_ts = round(time.time() * 1000) - self.max_rows * 100
18. # [(tableId, tableName, values),]
19. self.data = self._init_data()
20. self.infinity = infinity
22. def _init_data(self):
23. lines = self.samples * (self.table_count // 5 + 1)
24. data = []
25. for i in range(self.table_count):
26. table_name = self.table_name_prefix + str(i)
27. data.append((i, table_name, lines[i])) # tableId, row
28. return data
30. def __iter__(self):
31. self.row = 0
32. if not self.infinity:
33. return iter(self._iter_data())
34. else:
35. return self
37. def __next__(self):
38. """
39. next 1000 rows for each table.
40. return: {tableId:[row,...]}
41. """
42. return self._iter_data()
44. def _iter_data(self):
45. ts = []
46. for _ in range(1000):
47. self.current_ts += 100
48. ts.append(str(self.current_ts))
49. # add timestamp to each row
50. # [(tableId, ["tableName,ts,current,voltage,phase,location,groupId"])]
51. result = []
52. for table_id, table_name, values in self.data:
53. rows = [table_name + ',' + t + ',' + values for t in ts]
54. result.append((table_id, rows))
55. return result
58. if __name__ == '__main__':
59. datasource = MockDataSource('t', 10, False)
60. for data in datasource:
61. print(data)
run_write_task 函数
写进程每次从队列中取出尽量多的数据,并批量写入。
1. def run_write_task(task_id: int, queue: Queue, done_queue: Queue):
2. from sql_writer import SQLWriter
3. log = logging.getLogger(f"WriteTask-{task_id}")
4. writer = SQLWriter(get_connection)
5. lines = None
6. try:
7. while True:
8. over = False
9. lines = []
10. for _ in range(MAX_BATCH_SIZE):
11. try:
12. line = queue.get_nowait()
13. if line == _DONE_MESSAGE:
14. over = True
15. break
16. if line:
17. lines.append(line)
18. except Empty:
19. time.sleep(0.1)
20. if len(lines) > 0:
21. writer.process_lines(lines)
22. if over:
23. done_queue.put(_DONE_MESSAGE)
24. break
25. except KeyboardInterrupt:
26. pass
27. except BaseException as e:
28. log.debug(f"lines={lines}")
29. raise e
30. finally:
31. writer.close()
32. log.debug('write task over')
SQLWriter
SQLWriter 类封装了拼 SQL 和写数据的逻辑。所有的表都没有提前创建,而是在发生表不存在错误的时候,再以超级表为模板批量建表,然后重新执行 INSERT 语句。对于其它错误会记录当时执行的 SQL, 以便排查错误和故障恢复。这个类也对 SQL 是否超过最大长度限制做了检查,根据 TDengine 3.0 的限制由输入参数 maxSQLLength 传入了支持的最大 SQL 长度,即 1,048,576 。
1. import logging
2. import taos
5. class SQLWriter:
6. log = logging.getLogger("SQLWriter")
8. def __init__(self, get_connection_func):
9. self._tb_values = {}
10. self._tb_tags = {}
11. self._conn = get_connection_func()
12. self._max_sql_length = self.get_max_sql_length()
13. self._conn.execute("create database if not exists test")
14. self._conn.execute("USE test")
16. def get_max_sql_length(self):
17. rows = self._conn.query("SHOW variables").fetch_all()
18. for r in rows:
19. name = r[0]
20. if name == "maxSQLLength":
21. return int(r[1])
22. return 1024 * 1024
24. def process_lines(self, lines: [str]):
25. """
26. :param lines: [[tbName,ts,current,voltage,phase,location,groupId]]
27. """
28. for line in lines:
29. ps = line.split(",")
30. table_name = ps[0]
31. value = '(' + ",".join(ps[1:-2]) + ') '
32. if table_name in self._tb_values:
33. self._tb_values[table_name] += value
34. else:
35. self._tb_values[table_name] = value
37. if table_name not in self._tb_tags:
38. location = ps[-2]
39. group_id = ps[-1]
40. tag_value = f"('{location}',{group_id})"
41. self._tb_tags[table_name] = tag_value
42. self.flush()
44. def flush(self):
45. """
46. Assemble INSERT statement and execute it.
47. When the sql length grows close to MAX_SQL_LENGTH, the sql will be executed immediately, and a new INSERT statement will be created.
48. In case of "Table does not exit" exception, tables in the sql will be created and the sql will be re-executed.
49. """
50. sql = "INSERT INTO "
51. sql_len = len(sql)
52. buf = []
53. for tb_name, values in self._tb_values.items():
54. q = tb_name + " VALUES " + values
55. if sql_len + len(q) >= self._max_sql_length:
56. sql += " ".join(buf)
57. self.execute_sql(sql)
58. sql = "INSERT INTO "
59. sql_len = len(sql)
60. buf = []
61. buf.append(q)
62. sql_len += len(q)
63. sql += " ".join(buf)
64. self.create_tables()
65. self.execute_sql(sql)
66. self._tb_values.clear()
68. def execute_sql(self, sql):
69. try:
70. self._conn.execute(sql)
71. except taos.Error as e:
72. error_code = e.errno & 0xffff
73. # Table does not exit
74. if error_code == 9731:
75. self.create_tables()
76. else:
77. self.log.error("Execute SQL: %s", sql)
78. raise e
79. except BaseException as baseException:
80. self.log.error("Execute SQL: %s", sql)
81. raise baseException
83. def create_tables(self):
84. sql = "CREATE TABLE "
85. for tb in self._tb_values.keys():
86. tag_values = self._tb_tags[tb]
87. sql += "IF NOT EXISTS " + tb + " USING meters TAGS " + tag_values + " "
88. try:
89. self._conn.execute(sql)
90. except BaseException as e:
91. self.log.error("Execute SQL: %s", sql)
92. raise e
94. def close(self):
95. if self._conn:
96. self._conn.close()
99. if __name__ == '__main__':
100. def get_connection_func():
101. conn = taos.connect()
102. return conn
105. writer = SQLWriter(get_connection_func=get_connection_func)
106. writer.execute_sql(
107. "create stable if not exists meters (ts timestamp, current float, voltage int, phase float) "
108. "tags (location binary(64), groupId int)")
109. writer.execute_sql(
110. "INSERT INTO d21001 USING meters TAGS ('California.SanFrancisco', 2) "
111. "VALUES ('2021-07-13 14:06:32.272', 10.2, 219, 0.32)")
执行步骤
执行 Python 示例程序
-
前提条件
-
已安装 TDengine 客户端驱动
- 已安装 Python3, 推荐版本 >= 3.8
- 已安装 taospy
- 安装 faster-fifo 代替 python 内置的 multiprocessing.Queue
1. pip3 install faster-fifo
3. 点击上面的“查看源码”链接复制 fast_write_example.py 、 sql_writer.py 和 mockdatasource.py 三个文件。
4. 执行示例程序
1. python3 fast_write_example.py <READ_TASK_COUNT> <WRITE_TASK_COUNT> <TABLE_COUNT> <QUEUE_SIZE> <MAX_BATCH_SIZE>
下面是一次实际运行的输出, 机器配置 16 核 + 64G + 固态硬盘。
1. root@vm85$ python3 fast_write_example.py 8 8
2. 2022-07-14 19:13:45,869 [root] - READ_TASK_COUNT=8, WRITE_TASK_COUNT=8, TABLE_COUNT=1000, QUEUE_SIZE=1000000, MAX_BATCH_SIZE=3000
3. 2022-07-14 19:13:48,882 [root] - WriteTask-0 started with pid 718347
4. 2022-07-14 19:13:48,883 [root] - WriteTask-1 started with pid 718348
5. 2022-07-14 19:13:48,884 [root] - WriteTask-2 started with pid 718349
6. 2022-07-14 19:13:48,884 [root] - WriteTask-3 started with pid 718350
7. 2022-07-14 19:13:48,885 [root] - WriteTask-4 started with pid 718351
8. 2022-07-14 19:13:48,885 [root] - WriteTask-5 started with pid 718352
9. 2022-07-14 19:13:48,886 [root] - WriteTask-6 started with pid 718353
10. 2022-07-14 19:13:48,886 [root] - WriteTask-7 started with pid 718354
11. 2022-07-14 19:13:48,887 [root] - ReadTask-0 started with pid 718355
12. 2022-07-14 19:13:48,888 [root] - ReadTask-1 started with pid 718356
13. 2022-07-14 19:13:48,889 [root] - ReadTask-2 started with pid 718357
14. 2022-07-14 19:13:48,889 [root] - ReadTask-3 started with pid 718358
15. 2022-07-14 19:13:48,890 [root] - ReadTask-4 started with pid 718359
16. 2022-07-14 19:13:48,891 [root] - ReadTask-5 started with pid 718361
17. 2022-07-14 19:13:48,892 [root] - ReadTask-6 started with pid 718364
18. 2022-07-14 19:13:48,893 [root] - ReadTask-7 started with pid 718365
19. 2022-07-14 19:13:56,042 [DataBaseMonitor] - count=6676310 speed=667631.0
20. 2022-07-14 19:14:06,196 [DataBaseMonitor] - count=20004310 speed=1332800.0
21. 2022-07-14 19:14:16,366 [DataBaseMonitor] - count=32290310 speed=1228600.0
22. 2022-07-14 19:14:26,527 [DataBaseMonitor] - count=44438310 speed=1214800.0
23. 2022-07-14 19:14:36,673 [DataBaseMonitor] - count=56608310 speed=1217000.0
24. 2022-07-14 19:14:46,834 [DataBaseMonitor] - count=68757310 speed=1214900.0
25. 2022-07-14 19:14:57,280 [DataBaseMonitor] - count=80992310 speed=1223500.0
26. 2022-07-14 19:15:07,689 [DataBaseMonitor] - count=93805310 speed=1281300.0
27. 2022-07-14 19:15:18,020 [DataBaseMonitor] - count=106111310 speed=1230600.0
28. 2022-07-14 19:15:28,356 [DataBaseMonitor] - count=118394310 speed=1228300.0
29. 2022-07-14 19:15:38,690 [DataBaseMonitor] - count=130742310 speed=1234800.0
30. 2022-07-14 19:15:49,000 [DataBaseMonitor] - count=143051310 speed=1230900.0
31. 2022-07-14 19:15:59,323 [DataBaseMonitor] - count=155276310 speed=1222500.0
32. 2022-07-14 19:16:09,649 [DataBaseMonitor] - count=167603310 speed=1232700.0
33. 2022-07-14 19:16:19,995 [DataBaseMonitor] - count=179976310 speed=1237300.0
高效写入 - 图2note
使用 Python 连接器多进程连接 TDengine 的时候,有一个限制:不能在父进程中建立连接,所有连接只能在子进程中创建。 如果在父进程中创建连接,子进程再创建连接就会一直阻塞。这是个已知问题。
