流式查询
通过 WebSocket 和 Server-Sent Events 实现实时查询订阅。在新数据到达时将持续查询结果 流式推送到客户端,支持实时仪表板、告警管道和实时数据推送。
流式查询会按可配置的间隔自动重新执行,并将新结果推送到已连接的客户端。 与轮询不同,流式订阅维持持久连接,以最小延迟交付更新。
WebSocket 订阅
WebSocket 订阅提供全双工通信,支持实时查询流。客户端连接到 WebSocket 端点, 发送 SQL 订阅消息,然后持续接收结果更新。
端点
| URL | ws://host:port/ws/query/:db |
| 协议 | WebSocket (RFC 6455) |
| 消息格式 | JSON |
订阅消息
连接后,发送 JSON 消息以启动流式订阅:
{
"sql": "SELECT host, AVG(usage) as avg_cpu FROM cpu WHERE time > now() - interval '5 minutes' GROUP BY host",
"interval_ms": 5000,
"format": "json"
}
| 字段 | 类型 | 必填 | 说明 |
|---|---|---|---|
sql |
string | 是 | 每个间隔执行的 SQL 查询 |
interval_ms |
integer | 否 | 重新执行间隔(毫秒),默认值:1000 |
format |
string | 否 | 结果格式:json 或 arrow(默认:json) |
JavaScript 示例
// 连接到 WebSocket 流式端点
const ws = new WebSocket("ws://localhost:7000/ws/query/mydb");
ws.onopen = () => {
console.log("Connected to MynaDB streaming");
// 订阅流式查询
ws.send(JSON.stringify({
sql: "SELECT host, AVG(usage) as avg_cpu FROM cpu WHERE time > now() - interval '5 minutes' GROUP BY host",
interval_ms: 5000
}));
};
ws.onmessage = (event) => {
const message = JSON.parse(event.data);
if (message.type === "result") {
// 收到查询结果
console.log("Subscription:", message.subscription_id);
console.log("Rows:", message.data.length);
message.data.forEach(row => {
console.log(` ${row.host}: ${row.avg_cpu.toFixed(2)}%`);
});
} else if (message.type === "heartbeat") {
// 连接保活
console.log("Heartbeat received");
} else if (message.type === "error") {
console.error("Stream error:", message.message);
}
};
ws.onclose = (event) => {
console.log(`Connection closed: ${event.code} ${event.reason}`);
};
ws.onerror = (error) => {
console.error("WebSocket error:", error);
};
响应消息
服务器发送以下消息类型:
// 订阅确认
{
"type": "subscribed",
"subscription_id": "sub_a1b2c3d4",
"sql": "SELECT host, AVG(usage) ...",
"interval_ms": 5000
}
// 查询结果
{
"type": "result",
"subscription_id": "sub_a1b2c3d4",
"timestamp": 1704067200000,
"data": [
{"host": "server-01", "avg_cpu": 45.2},
{"host": "server-02", "avg_cpu": 62.8}
],
"row_count": 2,
"execution_time_ms": 12
}
// 心跳
{
"type": "heartbeat",
"timestamp": 1704067230000
}
// 错误
{
"type": "error",
"subscription_id": "sub_a1b2c3d4",
"message": "Table 'cpu' not found"
}
Server-Sent Events (SSE)
Server-Sent Events 提供了一种更简单的基于 HTTP 的流式机制。SSE 非常适合 只需接收数据(单向通信)且希望协议内置自动重连功能的浏览器客户端。
端点
| URL | GET /stream/query/:db?sql=...&interval_ms=... |
| Content-Type | text/event-stream |
| 方法 | GET |
| 参数 | 类型 | 必填 | 说明 |
|---|---|---|---|
sql |
string (query) | 是 | URL 编码的 SQL 查询 |
interval_ms |
integer (query) | 否 | 重新执行间隔(毫秒),默认值:1000 |
curl 示例
# 每 5 秒流式传输查询结果
curl -N "http://localhost:7000/stream/query/mydb?sql=SELECT%20host%2C%20AVG(usage)%20as%20avg_cpu%20FROM%20cpu%20WHERE%20time%20%3E%20now()%20-%20interval%20'5%20minutes'%20GROUP%20BY%20host&interval_ms=5000"
# 输出(Server-Sent Events 格式):
# event: result
# id: 1
# data: {"data":[{"host":"server-01","avg_cpu":45.2}],"row_count":1,"execution_time_ms":8}
#
# event: result
# id: 2
# data: {"data":[{"host":"server-01","avg_cpu":47.1}],"row_count":1,"execution_time_ms":6}
JavaScript EventSource API
// 使用查询参数构建 SSE URL
const sql = encodeURIComponent(
"SELECT host, AVG(usage) as avg_cpu FROM cpu WHERE time > now() - interval '5 minutes' GROUP BY host"
);
const url = `http://localhost:7000/stream/query/mydb?sql=${sql}&interval_ms=5000`;
// 创建 EventSource 连接(失败时自动重连)
const source = new EventSource(url);
// 监听查询结果
source.addEventListener("result", (event) => {
const result = JSON.parse(event.data);
console.log(`Received ${result.row_count} rows in ${result.execution_time_ms}ms`);
result.data.forEach(row => {
console.log(` ${row.host}: ${row.avg_cpu.toFixed(2)}%`);
});
});
// 监听心跳
source.addEventListener("heartbeat", (event) => {
console.log("Heartbeat:", event.data);
});
// 处理错误
source.onerror = (error) => {
console.error("SSE connection error:", error);
// EventSource 会自动尝试重新连接
};
// 停止流式传输
// source.close();
WebSocket 适合需要双向通信的场景(例如动态修改查询、在一个连接上管理
多个订阅)。SSE 对于只读流更简单,并通过 EventSource API 在浏览器中提供
内置的自动重连功能。
订阅管理
可以通过管理 API 列出和取消活跃的流式订阅。 这对于监控资源使用情况和终止失控查询非常有用。
列出活跃订阅
# 列出所有活跃的流式订阅
curl http://localhost:7000/stream/subscriptions
# 响应:
# {
# "subscriptions": [
# {
# "id": "sub_a1b2c3d4",
# "database": "mydb",
# "sql": "SELECT host, AVG(usage) ...",
# "interval_ms": 5000,
# "protocol": "websocket",
# "created_at": "2026-01-15T10:30:00Z",
# "last_execution": "2026-01-15T10:35:00Z",
# "execution_count": 60,
# "avg_execution_time_ms": 11
# }
# ],
# "count": 1
# }
取消订阅
# 按 ID 取消特定订阅
curl -X DELETE http://localhost:7000/stream/subscriptions/sub_a1b2c3d4
# 响应:
# {"status": "canceled", "subscription_id": "sub_a1b2c3d4"}
# 取消某个数据库的所有订阅
curl -X DELETE http://localhost:7000/stream/subscriptions?database=mydb
# 响应:
# {"status": "canceled", "count": 3}
WebSocket 订阅控制
也可以通过活跃的 WebSocket 连接直接管理订阅:
// 通过 WebSocket 取消特定订阅
ws.send(JSON.stringify({
action: "cancel",
subscription_id: "sub_a1b2c3d4"
}));
// 暂停订阅(停止执行,保持连接)
ws.send(JSON.stringify({
action: "pause",
subscription_id: "sub_a1b2c3d4"
}));
// 恢复已暂停的订阅
ws.send(JSON.stringify({
action: "resume",
subscription_id: "sub_a1b2c3d4"
}));
// 列出此连接上的活跃订阅
ws.send(JSON.stringify({
action: "list"
}));
配置
流式查询在 config.toml 的 [streaming] 部分进行配置。
[streaming]
# 启用流式查询端点(WebSocket 和 SSE)
enabled = true
# 每台服务器的最大并发流式订阅数
max_subscriptions = 100
# 心跳间隔(秒),用于保持连接活跃
heartbeat_interval_secs = 30
# 每个订阅的内部缓冲区大小(结果集数量)
buffer_size = 16
| 参数 | 默认值 | 说明 |
|---|---|---|
enabled |
true |
启用或禁用流式查询功能 |
max_subscriptions |
100 |
所有客户端的最大并发流式订阅数。防止过多活跃查询导致资源耗尽。 |
heartbeat_interval_secs |
30 |
向已连接客户端发送心跳消息的间隔(秒)。有助于检测过期连接并防止防火墙关闭空闲连接。 |
buffer_size |
16 |
每个订阅缓冲的结果集数量。如果客户端消费结果较慢,当缓冲区满时旧结果将被丢弃。 |
每个流式订阅都维护一个活跃的查询执行循环。请注意
max_subscriptions 和 interval_ms 的设置,避免查询引擎过载。
对于高频订阅(间隔 < 1 秒),建议使用持续聚合
来预计算结果。
使用场景
实时仪表板
构建随着新指标到达而自动更新的实时监控仪表板。 流式查询消除了客户端轮询的需求并降低了延迟。
// 仪表板:所有主机的实时 CPU 使用率
const ws = new WebSocket("ws://localhost:7000/ws/query/mydb");
ws.onopen = () => {
// 订阅聚合 CPU 指标
ws.send(JSON.stringify({
sql: `SELECT
host,
AVG(usage) as avg_cpu,
MAX(usage) as max_cpu,
MIN(usage) as min_cpu
FROM cpu
WHERE time > now() - interval '1 minute'
GROUP BY host
ORDER BY avg_cpu DESC`,
interval_ms: 2000
}));
};
ws.onmessage = (event) => {
const msg = JSON.parse(event.data);
if (msg.type === "result") {
updateDashboard(msg.data);
}
};
告警
使用流式查询实时检测异常并触发告警。 当阈值被突破时,立即通知运维人员。
// 告警:检测 CPU 使用率超过 90% 的主机
const ws = new WebSocket("ws://localhost:7000/ws/query/monitoring");
ws.onopen = () => {
ws.send(JSON.stringify({
sql: `SELECT host, AVG(usage) as avg_cpu
FROM cpu
WHERE time > now() - interval '2 minutes'
GROUP BY host
HAVING AVG(usage) > 90`,
interval_ms: 10000
}));
};
ws.onmessage = (event) => {
const msg = JSON.parse(event.data);
if (msg.type === "result" && msg.data.length > 0) {
msg.data.forEach(row => {
sendAlert({
severity: "critical",
host: row.host,
cpu: row.avg_cpu,
message: `CPU usage at ${row.avg_cpu.toFixed(1)}% on ${row.host}`
});
});
}
};
实时数据推送
将原始或轻度转换的数据流式传输到下游消费者,例如 数据管道、事件处理器或外部分析系统。
import json
import requests
# 使用 requests 库通过 SSE 流式传输数据
url = "http://localhost:7000/stream/query/mydb"
params = {
"sql": "SELECT * FROM sensor_readings WHERE time > now() - interval '10 seconds' ORDER BY time DESC LIMIT 50",
"interval_ms": 1000
}
response = requests.get(url, params=params, stream=True)
for line in response.iter_lines():
if line:
decoded = line.decode("utf-8")
if decoded.startswith("data: "):
data = json.loads(decoded[6:])
print(f"Received {data['row_count']} rows")
# 转发到下游管道...
process_batch(data["data"])