好的!以下是使用 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
)。