mcpField
A
azure-cosmos-java

azure-cosmos-java

github.com/sickn33数据与数据库48.7k62 次安装今天更新
代码仓库

关于 azure-cosmos-java

面向 Azure Cosmos DB NoSQL API 的 Java 客户端库,适用于需要数据库和容器操作的应用,可选择同步或响应式访问。它提供账户、数据库和容器级客户端,并支持配置一致性级别与连接模式。

主要功能

  1. 01同步与异步客户端
  2. 02账户、数据库和容器操作
  3. 03创建数据库与容器
  4. 04创建、读取、更新和删除项目
  5. 05参数化 SQL 查询
  6. 06配置一致性级别和连接模式

适用场景

  1. 01构建使用 Azure Cosmos DB 的 Java 应用
  2. 02执行响应式数据操作
  3. 03使用 SQL 参数查询项目

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/sickn33/agentic-awesome-skills --skill azure-cosmos-java

安装后在 Claude Code 中输入/azure-cosmos-java确认已加载。

详细介绍

Azure Cosmos DB SDK for Java

适用于 Azure Cosmos DB NoSQL API 的客户端库,支持全球分布和响应式模式。

安装

<dependency>
    <groupId>com.azure</groupId>
    <artifactId>azure-cosmos</artifactId>
    <version>{reviewed_exact_version}</version>
</dependency>

也可以使用 Azure SDK BOM:

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>com.azure</groupId>
            <artifactId>azure-sdk-bom</artifactId>
            <version>{bom_version}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

<dependencies>
    <dependency>
        <groupId>com.azure</groupId>
        <artifactId>azure-cosmos</artifactId>
    </dependency>
</dependencies>

环境变量

COSMOS_ENDPOINT=https://<account>.documents.azure.com:443/
COSMOS_KEY=<your-primary-key>

身份验证

基于密钥的身份验证
import com.azure.cosmos.CosmosClient;
import com.azure.cosmos.CosmosClientBuilder;

CosmosClient client = new CosmosClientBuilder()
    .endpoint(System.getenv("COSMOS_ENDPOINT"))
    .key(System.getenv("COSMOS_KEY"))
    .buildClient();
异步客户端
import com.azure.cosmos.CosmosAsyncClient;

CosmosAsyncClient asyncClient = new CosmosClientBuilder()
    .endpoint(serviceEndpoint)
    .key(key)
    .buildAsyncClient();
自定义配置
import com.azure.cosmos.ConsistencyLevel;
import java.util.Arrays;

CosmosClient client = new CosmosClientBuilder()
    .endpoint(serviceEndpoint)
    .key(key)
    .directMode(directConnectionConfig, gatewayConnectionConfig)
    .consistencyLevel(ConsistencyLevel.SESSION)
    .connectionSharingAcrossClientsEnabled(true)
    .contentResponseOnWriteEnabled(true)
    .userAgentSuffix("my-application")
    .preferredRegions(Arrays.asList("West US", "East US"))
    .buildClient();

客户端层级

类用途
CosmosClient / CosmosAsyncClient账户级操作
CosmosDatabase / CosmosAsyncDatabase数据库操作
CosmosContainer / CosmosAsyncContainer容器/项目操作

核心工作流

创建数据库
// Sync
var dbResponse = client.createDatabaseIfNotExists("myDatabase");
var database = client.getDatabase(dbResponse.getProperties().getId());

// Async with chaining
asyncClient.createDatabaseIfNotExists("myDatabase")
    .map(response -> asyncClient.getDatabase(response.getProperties().getId()))
    .subscribe(database -> System.out.println("Created: " + database.getId()));
创建容器
asyncClient.createDatabaseIfNotExists("myDatabase")
    .flatMap(dbResponse -> {
        String databaseId = dbResponse.getProperties().getId();
        return asyncClient.getDatabase(databaseId)
            .createContainerIfNotExists("myContainer", "/partitionKey")
            .map(containerResponse -> asyncClient.getDatabase(databaseId)
                .getContainer(containerResponse.getProperties().getId()));
    })
    .subscribe(container -> System.out.println("Container: " + container.getId()));
CRUD 操作
import com.azure.cosmos.models.PartitionKey;

CosmosAsyncContainer container = asyncClient
    .getDatabase("myDatabase")
    .getContainer("myContainer");

// Create
container.createItem(new User("1", "John Doe", "[email protected]"))
    .flatMap(response -> {
        System.out.println("Created: " + response.getItem());
        // Read
        return container.readItem(
            response.getItem().getId(),
            new PartitionKey(response.getItem().getId()),
            User.class);
    })
    .flatMap(response -> {
        System.out.println("Read: " + response.getItem());
        // Update
        User user = response.getItem();
        user.setEmail("[email protected]");
        return container.replaceItem(
            user,
            user.getId(),
            new PartitionKey(user.getId()));
    })
    .flatMap(response -> {
        // Delete
        return container.deleteItem(
            response.getItem().getId(),
            new PartitionKey(response.getItem().getId()));
    })
    .block();
查询文档
import com.azure.cosmos.models.CosmosQueryRequestOptions;
import com.azure.cosmos.util.CosmosPagedIterable;

CosmosContainer container = client.getDatabase("myDatabase").getContainer("myContainer");

var query = new com.azure.cosmos.models.SqlQuerySpec(
    "SELECT * FROM c WHERE c.status = @status",
    java.util.List.of(new com.azure.cosmos.models.SqlParameter("@status", "active")));
CosmosQueryRequestOptions options = new CosmosQueryRequestOptions();

CosmosPagedIterable<User> results = container.queryItems(
    query,
    options,
    User.class
);

results.forEach(user -> System.out.println("User: " + user.getName()));

核心概念

分区键

选择分区键时应考虑:

  • 高基数(不同值数量多)
  • 数据和请求分布均匀
  • 在查询中频繁使用
一致性级别
级别保证
Strong线性一致性
Bounded Staleness在有界延迟范围内保持一致前缀
Session在会话内保持一致前缀
Consistent Prefix读取不会看到顺序错乱的写入
Eventual不保证顺序
请求单位(RUs)

所有操作都会消耗 RUs。检查响应标头:

CosmosItemResponse<User> response = container.createItem(user);
System.out.println("RU charge: " + response.getRequestCharge());

最佳实践

  1. 重复使用 CosmosClient — 创建一次,并在整个应用程序中重复使用
  2. 在高吞吐量场景中使用异步客户端
  3. 谨慎选择分区键 — 会影响性能和可扩展性
  4. 在写入时启用内容响应,以便立即访问已创建的项目
  5. 为地理分布式应用程序配置首选区域
  6. 通过重试策略处理 429 错误(默认内置)
  7. 在生产环境中使用直接模式,以获得最低延迟

错误处理

import com.azure.cosmos.CosmosException;

try {
    container.createItem(item);
} catch (CosmosException e) {
    System.err.println("Status: " + e.getStatusCode());
    System.err.println("Message: " + e.getMessage());
    System.err.println("Request charge: " + e.getRequestCharge());
    
    if (e.getStatusCode() == 409) {
        System.err.println("Item already exists");
    } else if (e.getStatusCode() == 429) {
        System.err.println("Rate limited, retry after: " + e.getRetryAfterDuration());
    }
}

参考链接

资源URL
Maven 包https://central.sonatype.com/artifact/com.azure/azure-cosmos
API 文档https://azuresdkdocs.z19.web.core.windows.net/java/azure-cosmos/latest/index.html
产品文档https://learn.microsoft.com/azure/cosmos-db/
示例https://github.com/Azure-Samples/azure-cosmos-java-sql-api-samples
性能指南https://learn.microsoft.com/azure/cosmos-db/performance-tips-java-sdk-v4-sql
故障排除https://learn.microsoft.com/azure/cosmos-db/troubleshoot-java-sdk-v4-sql

适用场景

当需要执行概览中描述的工作流或操作时,可使用此技能。

限制

  • 仅当任务明确符合上述范围时,才使用此技能。
  • 不要将输出视为针对特定环境进行验证、测试或专家审查的替代品。
  • 如果缺少必要的输入、权限、安全边界或成功标准,请停止并请求澄清。

CRUD 示例要求提供一个 User 模型,其序列化后的分区键属性与容器路径匹配。示例中的 new PartitionKey(user.getId()) 仅当实际分区键值等于 ID 时才有效;否则,请传入模型真正的分区键值。请在获授权的测试容器中执行示例写入/删除操作,限制 RU 成本,并在关闭时关闭客户端。响应式订阅需要处理完成和错误;不要仅凭调用 subscribe() 就推断操作已完成。

评论

支持 Markdown