Skip to content

Fluss Java Client ​

概览 ​

Fluss Admin API 支持异步操作,用于管理和检查 Fluss 资源。它与 Fluss 集群通信,提供以下方法:

  • 管理数据库(创建、删除、列出)
  • 管理表(创建、删除、列出)
  • 管理分区(创建、删除、列出)
  • 获取元数据(schema、快照、服务器信息)

Fluss Table API 允许你与 Fluss 表交互以读写数据。

依赖 ​

要使用客户端,需要向 pom.xml 文件添加以下依赖。

xml
<!-- https://mvnrepository.com/artifact/org.apache.fluss/fluss-client -->
<dependency>
    <groupId>org.apache.fluss</groupId>
    <artifactId>fluss-client</artifactId>
    <version>1.1-SNAPSHOT</version>
</dependency>

初始化 ​

Connection 是 Fluss Java 客户端的主要入口点。它用于创建 Admin 和 Table 实例。 Connection 对象通过 ConnectionFactory 类创建,该类接受一个 Configuration 对象作为参数。 Configuration 对象包含连接 Fluss 集群所需的配置参数,例如 bootstrap servers。

Connection 对象是线程安全的,可在多个线程间共享。建议每个应用程序创建一个 Connection 实例,并用它创建多个 Admin 和 Table 实例。 而 Table 和 Admin 实例不是线程安全的,应为每个需要访问它们的线程单独创建。 不建议对 Table 和 Admin 进行缓存或池化。

创建新的 Admin 实例:

java
// creating Connection object to connect with Fluss cluster
Configuration conf = new Configuration(); 
conf.setString("bootstrap.servers", "localhost:9123");
Connection connection = ConnectionFactory.createConnection(conf);


// obtain Admin instance from the Connection
Admin admin = connection.getAdmin();
admin.listDatabases().get().forEach(System.out::println);

// obtain Table instance from the Connection
Table table = connection.getTable(TablePath.of("my_db", "my_table"));
System.out.println(table.getTableInfo());

如果你使用 SASL 认证,需要设置以下属性:

java
// creating Connection object to connect with Fluss cluster
Configuration conf = new Configuration(); 
conf.setString("bootstrap.servers", "localhost:9123");
conf.setString("client.security.protocol", "sasl");
conf.setString("client.security.sasl.mechanism", "PLAIN");
conf.setString("client.security.sasl.username", "alice");
conf.setString("client.security.sasl.password", "alice-secret");
Connection connection = ConnectionFactory.createConnection(conf);


// obtain Admin instance from the Connection
Admin admin = connection.getAdmin();
admin.listDatabases().get().forEach(System.out::println);

// obtain Table instance from the Connection
Table table = connection.getTable(TablePath.of("my_db", "my_table"));
System.out.println(table.getTableInfo());

操作方式 ​

FlussAdmin 中的所有方法都返回 CompletableFuture 对象。你可以通过两种方式处理它们:

阻塞操作 ​

对于同步行为,使用 get() 方法:

java
// Blocking call
List<String> databases = admin.listDatabases().get();

异步操作 ​

对于非阻塞行为,使用 thenAccept、thenApply 或其他方法:

java
admin.listDatabases()
    .thenAccept(databases -> {
        System.out.println("Available databases:");
        databases.forEach(System.out::println);
    })
    .exceptionally(ex -> {
        System.err.println("Failed to list databases: " + ex.getMessage());
        return null;
    });

创建数据库和表 ​

创建数据库 ​

java

// Create database descriptor
DatabaseDescriptor descriptor = DatabaseDescriptor.builder()
    .comment("This is a test database")
    .customProperty("owner", "data-team")
    .build();

// Create database (true means ignore if exists)
admin.createDatabase("my_db", descriptor, true) // non-blocking call
    .thenAccept(unused -> System.out.println("Database created successfully"))
    .exceptionally(ex -> {
        System.err.println("Failed to create database: " + ex.getMessage());
        return null;
    });

创建表 ​

java
Schema schema = Schema.newBuilder()
        .column("id", DataTypes.STRING())
        .column("age", DataTypes.INT())
        .column("created_at", DataTypes.TIMESTAMP())
        .column("is_active", DataTypes.BOOLEAN())
        .primaryKey("id")
        .build();

// Use the schema in a table descriptor
TableDescriptor tableDescriptor = TableDescriptor.builder()
        .schema(schema)
        .distributedBy(1, "id")  // Distribute by the id column with 1 buckets
//        .partitionedBy("")     // Partition by the partition key
        .build();

TablePath tablePath = TablePath.of("my_db", "user_table");
admin.createTable(tablePath, tableDescriptor, false).get(); // blocking call

TableInfo tableInfo = admin.getTableInfo(tablePath).get(); // blocking call
System.out.println(tableInfo);

集群检查 ​

自 Fluss 1.1 起,Admin.describeCluster() 会返回一个 ClusterDescription,其中包含 coordinator、存活的 TabletServer 节点(地址、机架、server tag 与软件版本)以及副本负载。这两个 TabletServer map 都以 server ID 作为键:

java
ClusterDescription cluster = admin.describeCluster().get();
int serverId = 1;
ServerNode node = cluster.getTabletServers().get(serverId);
String softwareVersion = node == null ? null : node.softwareVersion();
TabletServerDescription load = cluster.getTabletServerLoads().get(serverId);
boolean hasNoAssignedReplicas = load != null && load.getNumReplicas() == 0;

每个 TabletServer 都会报告其配置的 tablet-server.software-version,当该选项未设置或为空白时,则使用其 server JAR 的 Implementation-Version。例如,可以用 bin/tablet-server.sh start -Dtablet-server.software-version=1.1.0-vendor.2 启动一个实例,为该进程覆盖 JAR 版本。当版本不可用,或较旧的 server 未报告版本时,该值为 null。要跟踪滚动升级,可将每个预期 server ID 报告的版本与目标版本进行比较。对于未出现在存活节点 map 中的 ID,仍应计入预期数量。

负载 map 还包含仍持有副本的离线 server,因此某个 server 可能存在负载条目却没有存活的节点条目。没有副本的存活 server 其计数显式为 0。缺少负载条目表示统计信息不可用,不能作为该 server 已被迁空的证明。

在高可用部署中,getCoordinatorStandbys() 列出当前存活的备用 coordinator,不包含 getCoordinatorServer() 返回的活跃 coordinator。只要某个备用节点仍在集群中注册,它就会被列出,但这并不保证它已准备好接管 leader 角色。Coordinator 没有数字形式的 server ID,因此 ServerNode.id() 对它们没有意义。

该 API 需要对集群的 DESCRIBE 权限,并会在遇到可重试失败(包括 coordinator 地址变更)时刷新元数据并重试一次。不支持该 API 的 server 会返回 UnsupportedVersionException。对于基础的服务发现,Admin.getServerNodes() 依然会返回 coordinator 与存活的 TabletServer,且不需要集群的 DESCRIBE 权限;但它不包含 server tag、软件版本和副本负载。

表统计 ​

Admin API 提供 getTableStats 方法以获取表的统计信息,例如当前行数。

java
TablePath tablePath = TablePath.of("my_db", "user_table");
TableStats stats = admin.getTableStats(tablePath).get();
System.out.println("Row count: " + stats.getRowCount());

说明

Primary Key 表的 getTableStats 要求表使用默认的 changelog 模式('table.changelog.image' = 'FULL')。配置为 'table.changelog.image' = 'WAL' 的表不支持此功能。

表 API ​

写入器(Writers) ​

要向 Fluss 表写入数据,首先需要创建一个 Table 实例。

java
TablePath tablePath = TablePath.of("my_db", "user_table");
Table table = connection.getTable(tablePath);

在 Fluss 中既有 Primary Key Table 也有 Log Table,因此客户端会根据表类型提供不同的功能。 你可以使用 UpsertWriter 向 Primary Key 表写入数据,使用 AppendWriter 向 Log Table 写入数据。

java
table.newUpsert().createWriter();
table.newAppend().createWriter();

下面看看如何向 Primary Key 表写入数据。

java
List<User> users = List.of(
        new User("1", 20, LocalDateTime.now() , true),
        new User("2", 22, LocalDateTime.now() , true),
        new User("3", 23, LocalDateTime.now() , true),
        new User("4", 24, LocalDateTime.now() , true),
        new User("5", 25, LocalDateTime.now() , true)
);

注意: 目前 Fluss 中的数据以 rows 形式写入,因此我们需要将 POJO 转换为 GenericRow。关于更友好的数据写入 API,请参阅下方的 Java Typed API 小节。

java
Table table = connection.getTable(tablePath);

List<GenericRow> rows = users.stream().map(user -> {
    GenericRow row = new GenericRow(4);
    row.setField(0, BinaryString.fromString(user.getId()));
    row.setField(1, user.getAge());
    row.setField(2, TimestampNtz.fromLocalDateTime(user.getCreatedAt()));
    row.setField(3, user.isActive());
    return row;
}).collect(Collectors.toList());
        
System.out.println("Upserting rows to the table");
UpsertWriter writer = table.newUpsert().createWriter();

// upsert() is a non-blocking call that sends data to Fluss server with batching and timeout
rows.forEach(writer::upsert);

// call flush() to blocking the thread until all data is written successfully
writer.flush();

对于 Log Table,可以使用 AppendWriter API 写入数据。

java
table.newAppend().createWriter().append(row);

扫描器(Scanner) ​

要从 Fluss 表读取数据,首先需要创建一个 Scanner 实例。然后用户可以订阅表的 bucket 并 开始轮询记录。

java
LogScanner logScanner = table.newScan()
        .createLogScanner();

int numBuckets = table.getTableInfo().getNumBuckets();
System.out.println("Number of buckets: " + numBuckets);
for (int i = 0; i < numBuckets; i++) {     
    System.out.println("Subscribing to bucket " + i);
    logScanner.subscribeFromBeginning(i);
}

long scanned = 0;
Map<Integer, List<String>> rowsMap = new HashMap<>();

while (true) {     
    System.out.println("Polling for records...");
    ScanRecords scanRecords = logScanner.poll(Duration.ofSeconds(1));
    for (TableBucket bucket : scanRecords.buckets()) {
        for (ScanRecord record : scanRecords.records(bucket)) {
            InternalRow row = record.getRow();
            // Process the row
            ...
        }
    }
    scanned += scanRecords.count();
}

过滤下推(Filter Pushdown) ​

过滤下推可以减少 LogScanner 读取的数据量。Fluss 会针对 每个 record batch 中存储的列统计信息评估谓词,并跳过不可能包含匹配 行的 batch。

使用 PredicateBuilder 配合表的 RowType 构建谓词,并在创建扫描器之前 将其传给 Scan#filter(Predicate):

java
TableInfo tableInfo = table.getTableInfo();
PredicateBuilder predicateBuilder = new PredicateBuilder(tableInfo.getRowType());

int ageIndex = predicateBuilder.indexOf("age");
int activeIndex = predicateBuilder.indexOf("is_active");
Predicate predicate = PredicateBuilder.and(
        predicateBuilder.greaterOrEqual(ageIndex, 18),
        predicateBuilder.equal(activeIndex, true));

LogScanner logScanner = table.newScan()
        .filter(predicate)
        .createLogScanner();

该构建器支持比较谓词(equal、notEqual、lessThan、lessOrEqual、 greaterThan 和 greaterOrEqual)、空值检查、in、notIn、between、字符串谓词 (startsWith、endsWith 和 contains),以及 and/or 组合。

说明

  • 过滤下推仅支持使用 Arrow 日志格式的 Log Table ('table.log.format' = 'arrow')。
  • 每个被过滤的列都必须配置在表的 table.statistics.columns 属性中。 只有在启用统计之后写入的记录才能从该优化中受益。
  • 过滤在 record-batch 粒度上执行,可能产生误报。它不会 移除单个不匹配的行,因此在需要精确过滤时(例如使用 predicate.test(row)), 应用程序仍必须在每个返回的行上评估谓词。
  • BatchScanner(包括快照扫描)不支持过滤下推。

批量扫描 —— 完整的 Primary Key 表 ​

对于 Primary Key 表,BatchScanner 会读取表中每个存活的行一次 后停止。每个 bucket 都来自其 tablet server 上某个时间点的 RocksDB 快照: 来自某个 bucket 的行反映了该 bucket 扫描开启时刻的 KV 状态,且在该开启之后 对该 bucket 的写入对正在运行的扫描不可见。

Snapshot boundary is per-bucket

对于多 bucket 和分区表,createBatchScanner() 会在首次轮询时 独立打开每个 bucket 的快照。跨所有 bucket 不存在单一的全局表级时间点视图 —— 并发 写入可能落入尚未打开扫描器的 bucket。如果需要 严格的表级快照,请使用命名快照路径: 对 Admin#getLatestKvSnapshots(...) 返回的 snapshot id 调用 createBatchScanner(TableBucket, long snapshotId)。

这是周期性全量状态读取的构建块,例如:

  • 仪表盘 / 物化视图 —— 按计划重新读取 Primary Key 表的整个当前状态以刷新派生视图。
  • 缓存或搜索索引预热 —— 在启动时将 PK 表的每一行加载到 外部系统,并提供每 bucket 一致的快照保证。
  • 批量导出到 OLAP / 数据湖 —— 对表进行周期性全量快照 用于下游分析,补充通过 LogScanner 进行的流式 changelog 读取。

createBatchScanner()(无参数)扫描整张表;对于分区 表,它会自动扩展到所有分区 × bucket。使用 createBatchScanner(TableBucket) 扫描单个 bucket —— 在并行引擎中分发 扫描工作时非常有用。

java
try (BatchScanner scanner = table.newScan().createBatchScanner()) {
    while (true) {
        CloseableIterator<InternalRow> batch = scanner.pollBatch(Duration.ofSeconds(5));
        if (batch == null) {
            break; // end of scan
        }
        try {
            while (batch.hasNext()) {
                InternalRow row = batch.next();
                // process row
            }
        } finally {
            batch.close();
        }
    }
}

你也可以通过 project(...) 限制返回的列:

java
try (BatchScanner scanner = table.newScan()
        .project(new int[] {0, 2})        // or .project(Arrays.asList("id", "status"))
        .createBatchScanner()) {
    // ...
}

每次 RPC 的负载大小由 client.scanner.kv.fetch.max-bytes(默认 4mb)控制;服务端通过 kv.scanner.max-batch-size 进一步限制。注意 BatchScanner 不是 线程安全的 —— 不要跨线程共享实例。

查找(Lookup) ​

你也可以使用 Fluss API 对表执行查找。这对于根据主键或前缀键查询特定记录很有用。

java
// Lookup by primary key
LookupResult lookup = table.newLookup()
                .createLookuper()
                .lookup(rowKey)
                .get();
// Lookup by prefix key
LookupResult prefixLookup = table.newLookup()
        .lookupBy(prefixKeys)
        .createLookuper()
        .lookup(rowKey)
        .get();

多表扫描器与写入器 ​

通过 connection.getMultiTable() 获取的 MultiTable,允许单个扫描器或写入器跨多个表工作,而无需为每个表创建 Table 实例。 与 Table 类似,MultiTable 实例是轻量的,但不是线程安全的。

MultiTableLogScanner 按表路径订阅 bucket,每次轮询返回来自所有已订阅表的记录。 每条 MultiTableRecord 都携带表路径、写入时所使用的 schema 和 schema id、变更类型,以及底层的 ScanRecord。 多表扫描器不支持列投影和过滤下推;每条记录都携带完整的行。

java
MultiTable multiTable = connection.getMultiTable();
TablePath ordersPath = TablePath.of("my_db", "orders");
TablePath eventsPath = TablePath.of("my_db", "events");

try (MultiTableLogScanner scanner = multiTable.newMultiTableScan().createLogScanner()) {
    // non-partitioned table: (tablePath, bucket)
    scanner.subscribeFromBeginning(ordersPath, 0);
    // partitioned table: (tablePath, partitionId, bucket); using the wrong overload for a table throws
    for (PartitionInfo partition : admin.listPartitionInfos(eventsPath).get()) {
        scanner.subscribeFromBeginning(eventsPath, partition.getPartitionId(), 0);
    }

    while (true) {
        MultiTableRecords records = scanner.poll(Duration.ofSeconds(1));
        for (MultiTableRecord record : records) {
            TablePath tablePath = record.getTablePath();
            Schema schema = record.getSchema();
            InternalRow row = record.getRow();
            // Process the row
            ...
        }
        // Consumed offsets are available per table and per bucket
        for (TablePath tablePath : records.tablePaths()) {
            for (TableBucket bucket : records.buckets(tablePath)) {
                Long nextOffset = records.consumedUpToOffset(tablePath, bucket);
                ...
            }
        }
    }
}

如果某个已订阅的表被删除并重建,在取消订阅其过期 bucket 之前,对其进一步的订阅会失败。

MultiTableWriter 将每条记录路由到 MultiTableWriteRecord 中指定的表名。 Log Table 接受 forAppend,Primary Key 表接受 forUpsert 和 forDelete,每条记录必须携带该行所编码对应的 schema id。 每个写入器拥有自己的缓冲区与发送线程,因此请为每个流水线创建一个并在结束时关闭它;close() 会刷新待写入的记录。 被拒绝的记录(未知表、表类型不接受的操作、行与 schema 不匹配)仅通过返回的 future 报告,绝不会由 write() 或 flush() 抛出。

java
int ordersSchemaId = admin.getTableInfo(ordersPath).get().getSchemaId();
int usersSchemaId = admin.getTableInfo(usersPath).get().getSchemaId();

try (MultiTableWriter writer = multiTable.newMultiTableWrite().createWriter()) {
    // write() buffers the record and returns; the first write to a table blocks on a metadata lookup.
    // The future completes once the server acknowledges the record, or fails if the record is rejected.
    CompletableFuture<WriteResult> f1 =
            writer.write(MultiTableWriteRecord.forAppend(ordersPath, orderRow, ordersSchemaId));
    CompletableFuture<WriteResult> f2 =
            writer.write(MultiTableWriteRecord.forUpsert(usersPath, userRow, usersSchemaId));
    CompletableFuture<WriteResult> f3 =
            writer.write(MultiTableWriteRecord.forDelete(usersPath, userRow, usersSchemaId));

    // block until all buffered records are acknowledged
    writer.flush();
    // surface any rejected or failed records
    CompletableFuture.allOf(f1, f2, f3).get();
}

一种常见模式是在 Log Table 之间转发记录,复用扫描到的行和 schema id。 schema id 是针对目标表解析的,因此复用 record.getSchemaId() 仅在目标与源共享相同的 schema 历史(同一张表,或使用相同 DDL 创建的镜像表)时才有效;否则需传入布局与该行匹配的 target schema id。 当源是 Primary Key 表时,将 record.getChangeType() 映射到 forUpsert 或 forDelete,并跳过 UPDATE_BEFORE 记录。

java
for (MultiTableRecord record : scanner.poll(Duration.ofSeconds(1))) {
    writer.write(MultiTableWriteRecord.forAppend(targetPath, record.getRow(), record.getSchemaId()))
            .whenComplete((result, error) -> { if (error != null) { /* handle the rejected record */ } });
}

Java Typed API ​

Fluss 提供了 Typed API,允许你直接使用 Java POJO(Plain Old Java Objects)而非 InternalRow 对象工作。这通过将你的 Java 类自动映射到 Fluss 表 schema,简化了开发。

说明

Typed API 提供了更友好的使用体验,但由于 POJO 与内部行格式之间转换的开销,会带来一定的性能成本。对于高性能场景,建议使用更低层的 InternalRow API。

定义 POJO ​

要使用 Typed API,需定义一个 Java 类,其字段名和类型与你的 Fluss 表 schema 匹配。你可以使用 @ColumnName 来正确映射名称。

java
public class User {
    public Integer id;
    @ColumnName("first_name")
    public String firstName;
    @ColumnName("last_name")
    public String lastName;

    public User() {}

    public User(Integer id, String firstName, String lastName) {
        this.id = id;
        this.firstName = firstName;
        this.lastName = lastName;
    }
    
    // Getters, setters, equals, hashCode, toString...
}

支持的类型映射如下:

Fluss TypeJava Type
INTInteger
BIGINTLong
STRINGString
BOOLEANBoolean
FLOATFloat
DOUBLEDouble
DECIMALBigDecimal
DATELocalDate
TIMELocalTime
TIMESTAMPLocalDateTime
TIMESTAMP_LTZInstant
BINARY / BYTESbyte[]
ARRAYT[] / Collection
MAPMap
ROWNested POJO

嵌套 POJO(ROW 类型) ​

Fluss ROW 类型映射到嵌套 POJO。例如,如果你的表有一个 ROW<city STRING, zipCode INT> 类型的列,可以定义对应的 POJO:

java
public class Address {
    public String city;
    public Integer zipCode;

    public Address() {}
}

public class User {
    public Integer id;
    public String name;
    public Address address;  // Maps to ROW<city STRING, zipCode INT>

    public User() {}
}

嵌套 POJO 支持任意深度,也可用作 ARRAY 中的元素类型和 MAP 中的值类型:

java
public class Order {
    public Integer orderId;
    public Address[] shippingAddresses;      // ARRAY<ROW<...>>
    public Map<String, Address> addressMap;  // MAP<STRING, ROW<...>>

    public Order() {}
}

写入数据 ​

Append Writer ​

对于仅追加表(Log Table),使用 TypedAppendWriter。

java
TablePath path = TablePath.of("my_db", "users_log");
try (Table table = conn.getTable(path)) {
    TypedAppendWriter<User> writer = table.newAppend().createTypedWriter(User.class);
    
    writer.append(new User(1, "Alice", 30));
    writer.append(new User(2, "Bob", 25));
    
    writer.flush();
}

Upsert Writer ​

对于 Primary Key 表,使用 TypedUpsertWriter。

java
TablePath path = TablePath.of("my_db", "users_pk");
try (Table table = conn.getTable(path)) {
    TypedUpsertWriter<User> writer = table.newUpsert().createTypedWriter(User.class);
    
    // Insert or Update
    writer.upsert(new User(1, "Alice", 31));
    
    // Delete
    writer.delete(new User(1, null, null)); // Only PK fields are needed for delete
    
    writer.flush();
}

Partial Updates ​

你可以通过指定要更新的列来执行部分更新。

java
// Update only 'name' and 'age' for the user with id 1
Upsert upsert = table.newUpsert().partialUpdate("name", "age");
TypedUpsertWriter<User> writer = upsert.createTypedWriter(User.class);

User partialUser = new User();
partialUser.id = 1;
partialUser.name = "Alice Updated";
partialUser.age = 32;

writer.upsert(partialUser);
writer.flush();

读取数据 ​

使用 TypedLogScanner 以 POJO 形式读取数据。

java
Scan scan = table.newScan();
TypedLogScanner<User> scanner = scan.createTypedLogScanner(User.class);

try (CloseableIterator<TypedScanRecord<User>> iterator = scanner.subscribeFromBeginning()) {
    while (iterator.hasNext()) {
        TypedScanRecord<User> record = iterator.next();
        ChangeType changeType = record.getChangeType();
        User user = record.getValue();
        
        System.out.println(changeType + ": " + user);
    }
}

Projections ​

你也可以将投影与 Typed API 配合使用。不属于投影范围的 POJO 字段将为 null。

java
// Only read 'id' and 'name'
TypedLogScanner<User> scanner = table.newScan()
    .project("id", "name")
    .createTypedLogScanner(User.class);

Lookups ​

对于 Primary Key 表,你可以使用代表主键的 POJO 执行查找。

java
// Define a POJO for the key
public class UserId {
    public Integer id;
    
    public UserId(Integer id) { this.id = id; }
}

// Create a TypedLookuper
TypedLookuper<UserId> lookuper = table.newLookup().createTypedLookuper(UserId.class);

// Perform lookup
CompletableFuture<LookupResult> resultFuture = lookuper.lookup(new UserId(1));
LookupResult result = resultFuture.get();

if (result != null) {
    // Convert the result row back to a User POJO if needed
    // Note: You might need a RowToPojoConverter for this part if you want the full User object
    // or you can access fields from the InternalRow directly.
}

Performance Considerations ​

虽然 Typed API 提供了便利和类型安全,但它引入了你的 POJO 与 Fluss 内部二进制行格式(InternalRow)之间的一层额外转换。该转换过程(序列化与反序列化)会带来 CPU 开销。

基准测试表明,在写入和读取操作中,使用 Typed API 大约比直接使用 InternalRow API 慢 2 倍。

建议:

  • 在易用性、快速开发以及更看重类型安全而非原始性能的场景下,使用 Typed API。
  • 在吞吐量高、对延迟敏感、性能至关重要的应用中,使用 InternalRow API。

Fluss 中文文档