옵션
집 Skill 개발자 도구 azure-cosmos-java

azure-cosmos-java

microsoft/skills microsoft/skills

설정, 인증, CRUD 작업 및 쿼리 실행을 포함하여 Java용 Azure Cosmos DB SDK 사용에 대한 코드 예제와 지침을 제공합니다.

...모든 것을 확장하십시오
10
업데이트 된 시간 2026년 9월 12일

Java용 Azure Cosmos DB SDK

전역 분산 및 반응형 패턴을 지원하는 Azure Cosmos DB NoSQL API용 클라이언트 라이브러리.

설치


    com.azure
    azure-cosmos
    최신

또는 Azure SDK BOM을 사용하세요:


    
        
            com.azure
            azure-sdk-bom
            {bom_version}
            pom
            import
        
    



    
        com.azure
        azure-cosmos
    

환경 변수

COSMOS_ENDPOINT=https://.documents.azure.com:443/
COSMOS_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 컨테이너/항목 작업

핵심 워크플로우

데이터베이스 생성

// 동기식
client.createDatabaseIfNotExists("myDatabase")
    .map(response -> client.getDatabase(response.getProperties().getId()));

// 체이닝을 사용한 비동기 처리
asyncClient.createDatabaseIfNotExists("myDatabase")
    .map(response -> asyncClient.getDatabase(response.getProperties().getId()))
    .subscribe(database -> System.out.println("생성됨: " + 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");

// 생성
container.createItem(new User("1", "John Doe", "[email protected]"))
    .flatMap(response -> {
        System.out.println("생성됨: " + response.getItem());
        // 읽기
        return container.readItem(
            response.getItem().getId(),
            new PartitionKey(response.getItem().getId()),
            User.class);
    })
    .flatMap(response -> {
        System.out.println("읽기: " + response.getItem());
        // 업데이트
        User user = response.getItem();
        user.setEmail("[email protected]");
        return container.replaceItem(
            user,
            user.getId(),
            new PartitionKey(user.getId()));
    })
    .flatMap(response -> {
        // 삭제
        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");

String query = "SELECT * FROM c WHERE c.status = @status";
CosmosQueryRequestOptions options = new CosmosQueryRequestOptions();

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

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

핵심 개념

파티션 키

다음 조건을 충족하는 파티션 키를 선택하십시오:

  • 카드널리티가 높은(고유한 값이 많은)
  • 데이터와 요청의 균등한 분산
  • 쿼리에서 자주 사용되는 값

일관성 수준

수준 보장 사항
강력 선형화 가능성
유한한 지연 지연 시간이 유한한 일관된 접두사
세션 세션 내 일관된 접두사
일관성 있는 접두사 읽기 작업에서는 순서가 뒤바뀐 쓰기 작업을 절대 볼 수 없음
최종 순서 보장 없음

요청 단위(RU)

모든 작업은 RU를 소모합니다. 응답 헤더를 확인하세요:

CosmosItemResponse response = container.createItem(user);
System.out.println("RU 요금: " + 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("상태: " + e.getStatusCode());
    System.err.println("메시지: " + e.getMessage());
    System.err.println("요청 비용: " + e.getRequestCharge());
    
    if (e.getStatusCode() == 409) {
        System.err.println("항목이 이미 존재합니다");
    } else if (e.getStatusCode() == 429) {
        System.err.println("요청 제한에 걸렸습니다. 재시도 대기 시간: " + 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
GitHub에서 보기
---
name: azure-cosmos-java
description: Provides code examples and guidance for using the Azure Cosmos DB SDK for Java, including setup, authentication, CRUD operations, and querying.
license: MIT
---

# Azure Cosmos DB SDK for Java

Client library for Azure Cosmos DB NoSQL API with global distribution and reactive patterns.

## Installation

```xml
<dependency>
    <groupId>com.azure</groupId>
    <artifactId>azure-cosmos</artifactId>
    <version>LATEST</version>
</dependency>
```

Or use Azure SDK BOM:

```xml
<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>
```

## Environment Variables

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

## Authentication

### Key-based Authentication

```java
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();
```

### Async Client

```java
import com.azure.cosmos.CosmosAsyncClient;

CosmosAsyncClient asyncClient = new CosmosClientBuilder()
    .endpoint(serviceEndpoint)
    .key(key)
    .buildAsyncClient();
```

### With Customizations

```java
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();
```

## Client Hierarchy

| Class | Purpose |
|-------|---------|
| `CosmosClient` / `CosmosAsyncClient` | Account-level operations |
| `CosmosDatabase` / `CosmosAsyncDatabase` | Database operations |
| `CosmosContainer` / `CosmosAsyncContainer` | Container/item operations |

## Core Workflow

### Create Database

```java
// Sync
client.createDatabaseIfNotExists("myDatabase")
    .map(response -> client.getDatabase(response.getProperties().getId()));

// Async with chaining
asyncClient.createDatabaseIfNotExists("myDatabase")
    .map(response -> asyncClient.getDatabase(response.getProperties().getId()))
    .subscribe(database -> System.out.println("Created: " + database.getId()));
```

### Create Container

```java
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 Operations

```java
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();
```

### Query Documents

```java
import com.azure.cosmos.models.CosmosQueryRequestOptions;
import com.azure.cosmos.util.CosmosPagedIterable;

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

String query = "SELECT * FROM c WHERE c.status = @status";
CosmosQueryRequestOptions options = new CosmosQueryRequestOptions();

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

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

## Key Concepts

### Partition Keys

Choose a partition key with:
- High cardinality (many distinct values)
- Even distribution of data and requests
- Frequently used in queries

### Consistency Levels

| Level | Guarantee |
|-------|-----------|
| Strong | Linearizability |
| Bounded Staleness | Consistent prefix with bounded lag |
| Session | Consistent prefix within session |
| Consistent Prefix | Reads never see out-of-order writes |
| Eventual | No ordering guarantee |

### Request Units (RUs)

All operations consume RUs. Check response headers:

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

## Best Practices

1. **Reuse CosmosClient** — Create once, reuse throughout application
2. **Use async client** for high-throughput scenarios
3. **Choose partition key carefully** — Affects performance and scalability
4. **Enable content response on write** for immediate access to created items
5. **Configure preferred regions** for geo-distributed applications
6. **Handle 429 errors** with retry policies (built-in by default)
7. **Use direct mode** for lowest latency in production

## Error Handling

```java
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());
    }
}
```

## Reference Links

| Resource | URL |
|----------|-----|
| Maven Package | https://central.sonatype.com/artifact/com.azure/azure-cosmos |
| API Documentation | https://azuresdkdocs.z19.web.core.windows.net/java/azure-cosmos/latest/index.html |
| Product Docs | https://learn.microsoft.com/azure/cosmos-db/ |
| Samples | https://github.com/Azure-Samples/azure-cosmos-java-sql-api-samples |
| Performance Guide | https://learn.microsoft.com/azure/cosmos-db/performance-tips-java-sdk-v4-sql |
| Troubleshooting | https://learn.microsoft.com/azure/cosmos-db/troubleshoot-java-sdk-v4-sql |

모든 파일

0개 파일

azure-cosmos-java 설치

스킬 파일을 다운로드하여 .claude/skills/ 디렉터리에 압축을 풀어주세요.

ZIP 다운로드

저장소를 클론하고 스킬 파일을 프로젝트에 복사하세요.

git clone https://github.com/microsoft/skills/tree/main/.github/plugins/azure-sdk-java/skills/azure-cosmos-java # Copy SKILL.md to your .claude/skills/ directory

복사 복사
빠른 설정: 스킬 폴더를 .claude/skills/로 복사하세요. Claude가 해당 스킬을 자동으로 감지하여 사용할 것입니다.
저장소 microsoft/skills

관련 스킬

algorithmic-art
업데이트 된 시간 2026년 8월 27일
receiving-code-review
업데이트 된 시간 2026년 9월 3일
tech-debt-tracker
업데이트 된 시간 2026년 8월 29일
senior-backend
업데이트 된 시간 2026년 8월 30일
OR