-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsession-pool.ts
More file actions
187 lines (161 loc) · 5.96 KB
/
Copy pathsession-pool.ts
File metadata and controls
187 lines (161 loc) · 5.96 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
/**
* SessionPool Example
*
* This example demonstrates how to use SessionPool for efficient connection
* management in high-concurrency scenarios, including explicit session management.
*/
import { SessionPool, PoolConfigBuilder, TreeTablet, TSDataType } from "../src";
async function main() {
console.log("=== SessionPool Example ===\n");
// Method 1: Traditional constructor (backward compatible)
console.log("Creating session pool using traditional constructor...");
const pool1 = new SessionPool("localhost", 6667, {
username: "root",
password: "root",
maxPoolSize: 10,
minPoolSize: 2,
maxIdleTime: 60000,
waitTimeout: 60000,
});
// Method 2: Using Builder pattern (recommended)
console.log("Creating session pool using Builder pattern...");
const pool2 = new SessionPool(
new PoolConfigBuilder()
.host("localhost")
.port(6667)
.username("root")
.password("root")
.maxPoolSize(10)
.minPoolSize(2)
.maxIdleTime(60000)
.waitTimeout(60000)
.build(),
);
// For demo purposes, we'll use pool1
const pool = pool1;
try {
// Initialize the pool
console.log("\nInitializing session pool...");
await pool.init();
console.log("Pool initialized with", pool.getPoolSize(), "connections");
// Create database
console.log("\nCreating database...");
await pool.executeNonQueryStatement("CREATE DATABASE root.pool_example");
// Create timeseries
console.log("Creating timeseries...");
await pool.executeNonQueryStatement(
"CREATE TIMESERIES root.pool_example.sensor1.value WITH DATATYPE=FLOAT",
);
// Approach 1: Using pool methods directly (automatic session management)
console.log("\n--- Approach 1: Automatic session management ---");
console.log("Executing concurrent queries...");
const promises = [];
for (let i = 0; i < 20; i++) {
promises.push(
pool.executeQueryStatement("SHOW DATABASES").then(async (dataSet) => {
let count = 0;
while (await dataSet.hasNext()) {
dataSet.next();
count++;
}
await dataSet.close();
console.log(`Query ${i + 1} completed with ${count} rows`);
}),
);
}
await Promise.all(promises);
console.log("All concurrent queries completed");
// Approach 2: Explicit session management (new API)
console.log("\n--- Approach 2: Explicit session management ---");
console.log("Getting a session from the pool...");
const session = await pool.getSession();
try {
console.log("Executing operations with explicit session...");
// Insert data using TreeTablet class with addRow
const tablet = new TreeTablet(
"root.pool_example.sensor1",
["value"],
[TSDataType.FLOAT]
);
tablet.addRow(Date.now(), [42.5]);
tablet.addRow(Date.now() + 1000, [43.0]);
await session.insertTablet(tablet);
console.log("Tree tablet data inserted via explicit session");
// Query data
const dataSet = await session.executeQueryStatement(
"SELECT * FROM root.pool_example.sensor1",
);
let rowCount = 0;
while (await dataSet.hasNext()) {
dataSet.next();
rowCount++;
}
await dataSet.close();
console.log("Query result:", rowCount, "rows");
} finally {
// Always release the session back to the pool
pool.releaseSession(session);
console.log("Session released back to the pool");
}
// Check pool statistics
console.log("\nPool statistics:");
console.log("Total connections:", pool.getPoolSize());
console.log("Available connections:", pool.getAvailableSize());
console.log("In-use connections:", pool.getInUseSize());
// Enhanced metrics
console.log("\nEnhanced pool metrics:");
console.log("Total (new API):", pool.totalCount);
console.log("Idle (new API):", pool.idleCount);
console.log("Active (new API):", pool.activeCount);
console.log("Waiting requests:", pool.waitingCount);
// Comprehensive statistics
const stats = pool.getPoolStats();
console.log("\nComprehensive stats:", stats);
// Approach 3: Concurrent batch insertion (NEW API)
console.log("\n--- Approach 3: Concurrent batch insertion (insertTabletsParallel) ---");
const tablets = [];
const batchTime = Date.now();
for (let i = 0; i < 20; i++) {
tablets.push({
deviceId: `root.pool_example.batch_sensor${i}`,
measurements: ["value"],
dataTypes: [TSDataType.FLOAT],
timestamps: [batchTime + i * 1000],
values: [[100.0 + i]],
});
}
console.log(`Inserting ${tablets.length} tablets concurrently...`);
const startTime = Date.now();
await pool.insertTabletsParallel(tablets, { concurrency: 5 });
const elapsed = Date.now() - startTime;
console.log(`Inserted ${tablets.length} tablets in ${elapsed}ms (${(tablets.length * 1000 / elapsed).toFixed(2)} tablets/sec)`);
// Approach 4: Generic parallel execution (NEW API)
console.log("\n--- Approach 4: Generic parallel execution (executeParallel) ---");
const deviceNames = ["parallel_d1", "parallel_d2", "parallel_d3", "parallel_d4"];
console.log(`Creating ${deviceNames.length} timeseries in parallel...`);
const results = await pool.executeParallel(
deviceNames,
async (session, deviceName) => {
try {
await session.executeNonQueryStatement(
`CREATE TIMESERIES root.pool_example.${deviceName}.value WITH DATATYPE=FLOAT`
);
} catch {
// Ignore if already exists
}
return `Created ${deviceName}`;
},
{ concurrency: 4 }
);
console.log("Results:", results);
} catch (error) {
console.error("Error:", error);
} finally {
// Close the pool
console.log("\nClosing session pool...");
await pool.close();
await pool2.close();
console.log("Pool closed");
}
}
main().catch(console.error);