Docs
文档目录

Server SDK(Java)

Java 后端 / 工具以项目 API Key 调用 Server SDK(io.agentbase:agentbase-java-sdk)。API Key 请求跳过行级权限检查(hasRole),只存受控服务端。Node / Python / Go 面见同目录 nodejs.md / python.md / go.md。

制品与安装

Java SDK 以 ZIP 交付包发布(不发布到 Maven registry),托管在 agentbase-sdks release v2.10.0;下载、双层 SHA256SUMS 校验与 mvn install:install-file 完整步骤见 ../integration.md(路径二)与 ../examples/java.md「获取与校验」。运行时:Java 11 source/target(OpenJDK 11/17 可跑);transport 为 OkHttp(解包目录 lib/ 携带运行时依赖,直接用 JAR 时必须连 lib/ 一起分发)。

初始化

import io.agentbase.Client;
import io.agentbase.services.TablesDB;
import io.agentbase.Query;
import io.agentbase.ID;

Client client = new Client()
    .setEndpoint(System.getenv("APPBASE_ENDPOINT"))   // https://appbuild.oceanbase.com/v1
    .setProject(System.getenv("APPBASE_PROJECT_ID"))
    .setKey(System.getenv("APPBASE_API_KEY"));        // 最小 scope 的项目 API Key

TablesDB tables = new TablesDB(client);               // 服务逐个构造

调用风格:方法为同步位置参数,默认返回类型化 model 或 Map<String,Object>;自定义 POJO 用 new TypeToken<MyPojo>(){}.getType() 重载。

Custom Token 签发

Users users = new Users(client);
Token token = users.createToken("<userId>", null, null);   // { secret, expire }
// 浏览器端用 Client SDK:account.createSession({ userId, secret: token.secret })

users.createJWT 是给用户签发短期 JWT(约 15 分钟)用于服务间带用户身份调用,不是 Session 通道;Tokens 服务是 Storage 文件临时令牌,与用户令牌无关。

客户端配置、超时与类型反序列化约定

io.agentbase.Client 基于 OkHttp 构建,支持链式配置鉴权头、语言、自签名证书及底层连接池参数:

Client 方法作用说明
setEndpoint(String)设置 API 根路径如 https://appbuild-sit.oceanbase.com/v1 或 https://appbuild.oceanbase.com/v1。
setProject(String)设置 X-Appwrite-Project目标项目 ID(如演示项目 enterprise-ai-hub-210)。
setKey(String)设置 X-Appwrite-Key服务端项目 API Key,跳过 RLS 检查,按最小 scope 授权。
setJWT(String)设置 X-Appwrite-JWT代表特定用户执行受 RLS 约束的服务端调用。
setSession(String)设置 X-Appwrite-Session转发浏览器登录会话。
setLocale(String)设置 X-Appwrite-Locale指定国际化语言(如 zh-CN)。
setSelfSigned(boolean)自签名 TLS 证书开关仅私有测试环境使用,生产环境保持 false。
addHeader(String, String)追加自定义请求头用于注入分布式追踪头或自定义幂等标识。

5 分钟端到端示例(建表、写行、游标分页与文件上传)

以下示例演示在演示项目 enterprise-ai-hub-210 中操作业务库 enterprise_biz_db 的工单表 customer_tickets,并使用游标分页(Query.cursorAfter)与 InputFile 上传文件:

import io.agentbase.Client;
import io.agentbase.ID;
import io.agentbase.Query;
import io.agentbase.exceptions.AppBaseException;
import io.agentbase. models.InputFile;
import io.agentbase.models.Row;
import io.agentbase.models.RowList;
import io.agentbase.services.Storage;
import io.agentbase.services.TablesDB;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class EnterpriseTicketExample {
    public static void main(String[] args) throws Exception {
        Client client = new Client()
            .setEndpoint(System.getenv().getOrDefault("APPBASE_ENDPOINT", "https://appbuild-sit.oceanbase.com/v1"))
            .setProject(System.getenv().getOrDefault("APPBASE_PROJECT_ID", "enterprise-ai-hub-210"))
            .setKey(System.getenv("APPBASE_API_KEY"));

        TablesDB tables = new TablesDB(client);
        Storage storage = new Storage(client);

        // 1. 写入一条企业客户工单行
        Row created = tables.createRow(
            "enterprise_biz_db",
            "customer_tickets",
            ID.unique(),
            Map.of(
                "ticketNo", "TK-20261022-005",
                "title", "OceanBase 向量索引构建参数咨询",
                "status", "open",
                "priority", "high"
            ),
            List.of("read(\"any\")")
        );
        System.out.println("Created row ID: " + created.getId());

        // 2. 使用 Query.cursorAfter 游标分页拉取全量未完结工单(禁用 total 计数提升性能)
        String cursor = null;
        long pageSize = 50L;
        while (true) {
            List<String> queries = new ArrayList<>();
            queries.add(Query.equal("status", List.of("open", "in_progress")));
            queries.add(Query.orderAsc("$id"));
            queries.add(Query.limit(pageSize));
            if (cursor != null) {
                queries.add(Query.cursorAfter(cursor));
            }

            RowList<Map<String, Object>> page = tables.listRows(
                "enterprise_biz_db",
                "customer_tickets",
                queries,
                null,
                false // total=false 避免大表 count(*) 开销
            );
            List<Row<Map<String, Object>>> rows = page.getRows();
            if (rows.isEmpty()) {
                break;
            }
            for (Row<Map<String, Object>> row : rows) {
                System.out.println("Ticket: " + row.getId() + " -> " + row.getData().get("title"));
            }
            if (rows.size() < pageSize) {
                break;
            }
            cursor = rows.get(rows.size() - 1).getId();
        }

        // 3. 上传本地文档至知识库源文件桶 kb_enterprise_docs
        var uploaded = storage.createFile(
            "kb_enterprise_docs",
            ID.unique(),
            InputFile.fromFile(new File("/tmp/智能客服SOP标准作业手册.md")),
            null
        );
        System.out.println("Uploaded file ID: " + uploaded.getId());
    }
}

生产环境重试与异常处理规范

Java SDK 的所有服务方法在遇到非 2xx 响应时抛出受检异常 io.agentbase.exceptions.AppBaseException。生产代码应根据 e.getCode() 区分幂等可重试错误(429 限流、502/503/504 网关瞬态或只读切换排空)与不可重试的调用方错误(400 参数不合法、401/403 Key 或 scope 缺失、404 资源不存在、409 唯一键或版本冲突):

public static <T> T executeWithRetry(java.util.concurrent.Callable<T> action, int maxAttempts) throws Exception {
    for (int attempt = 1; attempt <= maxAttempts; attempt++) {
        try {
            return action.call();
        } catch (io.agentbase.exceptions.AppBaseException e) {
            int code = e.getCode() != null ? e.getCode() : 0;
            boolean retryable = (code == 429 || code == 502 || code == 503 || code == 504);
            if (!retryable || attempt == maxAttempts) {
                throw e;
            }
            Thread.sleep(Math.min(1000L * (1L << (attempt - 1)), 8000L));
        }
    }
    throw new IllegalStateException("Unreachable");
}

功能面导航

服务面与 Node 面同构(PascalCase 类、驼峰方法),全量映射见 nodejs.md「功能面导航」;各功能页:数据库、存储、函数、站点、用户、团队、消息、记忆、知识库、LLM Gateway、AI Gateway、可观测、审核、横切服务。

Java 面特有差异:

与 Console SDK 并用

两个 SDK 的 Client 同名、namespace 独立(io.agentbase.Client vs io.agentbase.console.Client,见 ../console-sdk/java.md)。同一个 Java 文件只 import 一个,另一个用全限定类名;两边的 model / enum / service 禁止混用。

错误处理

try {
    tables.getRow("app-db", "tasks", rowId, null, null);
} catch (io.agentbase.exceptions.AppBaseException e) {
    System.err.println("HTTP " + e.getCode() + " type=" + e.getType() + " msg=" + e.getMessage());
    // 413 存储超限 / 429 限频 / 401·403 认证或 scope
}

示例指引