好的!以下是使用 TimescaleDB 的 Java 示例(基于 JDBC,因为 TimescaleDB 是 PostgreSQL 的扩展,官方未提供独立的 Java SDK):
1. 添加依赖(Maven)
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.3.1</version>
</dependency>
2. 连接 TimescaleDB
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class TimescaleDBExample {
public static void main(String[] args) {
String url = "jdbc:postgresql://localhost:5432/mydb"; // 数据库地址
String user = "postgres";
String password = "password";
try (Connection connection = DriverManager.getConnection(url, user, password)) {
System.out.println("成功连接到 TimescaleDB!");
// 执行后续操作(如创建表、插入数据、查询等)
} catch (SQLException e) {
e.printStackTrace();
}
}
}
3. 创建时序表(Hypertable)
步骤:
- 创建基础表:
CREATE TABLE cpu_usage (
time TIMESTAMPTZ NOT NULL,
host TEXT NOT NULL,
load DOUBLE PRECISION
);
- 转换为超表:
SELECT create_hypertable('cpu_usage', 'time');
Java 执行 SQL:
String sql = "SELECT create_hypertable('cpu_usage', 'time');");
try (Statement stmt = connection.createStatement()) {
stmt.execute(sql);
System.out.println("时序表创建成功!");
}
4. 插入数据
String insertSql = "INSERT INTO cpu_usage (time, host, load) VALUES ('2025-03-08 23:30:00+08:00', 'server01', 0.85)";
try (PreparedStatement pstmt = connection.prepareStatement(insertSql)) {
pstmt.executeUpdate();
System.out.println("数据插入成功!");
}
5. 查询数据
查询最近 5 分钟的数据:
SELECT * FROM cpu_usage
WHERE time >= NOW() - INTERVAL '5 minutes';
Java 执行查询:
String query = "SELECT * FROM cpu_usage WHERE time >= NOW() - INTERVAL '5 minutes';";
try (Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery(query)) {
while (rs.next()) {
System.out.println("Time: " + rs.getTimestamp("time"));
System.out.println("Host: " + rs.getString("host"));
System.out.println("Load: " + rs.getDouble("load"));
}
}
6. 创建保留策略(Retention Policy)
TimescaleDB 的保留策略通过 SQL 实现:
ALTER TABLE cpu_usage
SET (timescaledb(retention_period = '30 days'));
Java 执行:
String retentionSql = "ALTER TABLE cpu_usage SET (timescaledb(retention_period = '30 days'));";
try (Statement stmt = connection.createStatement()) {
stmt.execute(retentionSql);
System.out.println("保留策略创建成功!");
}
注意事项
- 时间格式:插入时间时需使用
TIMESTAMPTZ
格式(带时区)。 - 批量操作:使用
PreparedStatement
和批处理提高写入性能。 - 连接池:生产环境中建议使用 HikariCP 或 PostgreSQL 的连接池。
- SQL 方言:TimescaleDB 支持部分 PostgreSQL 扩展语法(如
CREATE HYPERTABLE
)。