在本快速入门中,你将使用用于 Java 的 Azure SDK 部署基本的 Azure Cosmos DB for NoSQL 应用程序。 Azure Cosmos DB for NoSQL 是一种无架构数据存储,允许应用程序在云中存储非结构化数据。 使用用于 Java 的 Azure SDK 查询容器中的数据,并针对单个项执行常见作。
API 参考文档 | 库源代码 | 包 (Maven) | Azure Developer CLI
先决条件
- Azure 开发人员 CLI
- Docker Desktop
- Java 21
如果你没有 Azure 帐户,请在开始之前创建一个试用帐户。
初始化项目
使用 Azure 开发人员 CLI (azd) 创建 Azure Cosmos DB for NoSQL 帐户并部署容器化示例应用程序。 示例应用程序使用客户端库来管理、创建、读取和查询示例数据。
- 在空目录中打开终端。 
- 如果尚未经过身份验证,请使用 - azd auth login向 Azure Developer CLI 进行身份验证。 按照该工具指定的步骤,使用首选 Azure 凭据向 CLI 进行身份验证。- azd auth login
- 使用 - azd init来初始化项目。- azd init --template cosmos-db-nosql-java-quickstart
- 在初始化期间,配置唯一的环境名称。 
- 使用 - azd up部署 Azure Cosmos DB 帐户。 Bicep 模板还部署示例 Web 应用程序。- azd up
- 在预配过程中,选择订阅、所需位置和目标资源组。 等待预配过程完成。 此过程可能需要大约 5 分钟。 
- 预配 Azure 资源后,输出中将包含指向正在运行的 Web 应用程序的 URL。 - Deploying services (azd deploy) (✓) Done: Deploying service web - Endpoint: <https://[container-app-sub-domain].azurecontainerapps.io> SUCCESS: Your application was provisioned and deployed to Azure in 5 minutes 0 seconds.
- 使用控制台中的 URL 在浏览器中导航到 Web 应用程序。 观察正在运行的应用的输出。 
              
               
              
              
            
安装客户端库
客户端库可以通过 Maven 作为 azure-spring-data-cosmos 包提供。
- 导航到 - /src/web文件夹并打开“pom.xml”文件。
- 如果它尚不存在,请为 - azure-spring-data-cosmos包添加一个条目。- <dependency> <groupId>com.azure</groupId> <artifactId>azure-spring-data-cosmos</artifactId> </dependency>
- 此外,如果 - azure-identity包尚不存在,请为其添加另一个依赖项。- <dependency> <groupId>com.azure</groupId> <artifactId>azure-identity</artifactId> </dependency>
导入库文件
将所有必需的命名空间导入你的应用程序代码。
import com.azure.cosmos.CosmosClientBuilder;
import com.azure.cosmos.models.PartitionKey;
import com.azure.identity.DefaultAzureCredential;
import com.azure.identity.DefaultAzureCredentialBuilder;
import com.azure.spring.data.cosmos.config.AbstractCosmosConfiguration;
import com.azure.spring.data.cosmos.config.CosmosConfig;
import com.azure.spring.data.cosmos.core.mapping.Container;
import com.azure.spring.data.cosmos.core.mapping.PartitionKey;
import com.azure.spring.data.cosmos.repository.CosmosRepository;
import com.azure.spring.data.cosmos.repository.Query;
import com.azure.spring.data.cosmos.repository.config.EnableCosmosRepositories;
对象模型
| 名称 | 描述 | 
|---|---|
| EnableCosmosRepositories | 此类型是用于配置存储库以访问 Azure Cosmos DB for NoSQL 的方法修饰器。 | 
| CosmosRepository | 此类是主客户端类,用于管理容器中的数据。 | 
| CosmosClientBuilder | 此类是一个工厂,用于创建供存储库使用的客户端。 | 
| Query | 此类型是一个方法修饰器,用于指定存储库执行的查询。 | 
代码示例
模板中的示例代码使用名为 cosmicworks 的数据库和名为 products 的容器。 
              products 容器包含每个产品的名称、类别、数量、唯一标识符和销售标志等详细信息。 该容器使用 /category 属性作为逻辑分区键。
验证客户端
首先,此示例创建了一个继承自 AbstractCosmosConfiguration 的新类,以配置与 Azure Cosmos DB for NoSQL 的连接。
@Configuration
@EnableCosmosRepositories
public class CosmosConfiguration extends AbstractCosmosConfiguration {
}
在配置类中,此示例创建 CosmosClientBuilder 类的新实例,并使用 DefaultAzureCredential 实例配置身份验证。
@Bean
public CosmosClientBuilder getCosmosClientBuilder() {
    DefaultAzureCredential credential = new DefaultAzureCredentialBuilder()
        .build();
        
    return new CosmosClientBuilder()
        .endpoint("<azure-cosmos-db-nosql-account-endpoint>")
        .credential(credential);
}
获取数据库
在配置类中,示例实现了一个方法,用于返回名为 cosmicworks 的现有数据库的名称。
@Override
protected String getDatabaseName() {
    return "cosmicworks";
}
获取容器
使用 Container 方法修饰器来配置类以表示容器中的项。 创建类以包含要序列化为 JSON 的所有成员。 在此示例中,该类型具有唯一标识符以及用于类别、名称、数量、价格和清除的字段。
@Container(containerName = "products", autoCreateContainer = false)
public class Item {
    private String id;
    private String name;
    private Integer quantity;
    private Boolean sale;
    @PartitionKey
    private String category;
    // Extra members omitted for brevity
}
创建物品
使用 repository.save 在容器中创建某个项。
Item item = new Item(
    "aaaaaaaa-0000-1111-2222-bbbbbbbbbbbb",
    "gear-surf-surfboards",
    "Yamba Surfboard",
    12,
    false
);
Item created_item = repository.save(item);
读取项
同时使用唯一标识符 (id) 和分区键字段来执行点读取操作。 使用 repository.findById 以有效检索特定项。
PartitionKey partitionKey = new PartitionKey("gear-surf-surfboards");
Optional<Item> existing_item = repository.findById("aaaaaaaa-0000-1111-2222-bbbbbbbbbbbb", partitionKey);
if (existing_item.isPresent()) {
    // Do something
}
查询项
通过在存储库的接口中定义一个查询,对容器中的多个项执行查询。 此示例使用 Query 方法修饰器来定义执行此参数化查询的方法:
SELECT * FROM products p WHERE p.category = @category
@Repository
public interface ItemRepository extends CosmosRepository<Item, String> {
    @Query("SELECT * FROM products p WHERE p.category = @category")
    List<Item> getItemsByCategory(@Param("category") String category);
}
通过使用 repository.getItemsByCategory 提取查询的所有结果。 遍历查询的结果。
List<Item> items = repository.getItemsByCategory("gear-surf-surfboards");
for (Item item : items) {
    // Do something
}
探索您的数据
使用适用于 Azure Cosmos DB 的 Visual Studio Code 扩展来浏览 NoSQL 数据。 可以执行核心数据库操作,这些操作包括但不限于:
- 使用剪贴簿或查询编辑器执行查询
- 修改、更新、创建和删除项
- 从其他源导入批量数据
- 管理数据库和容器
有关详细信息,请参阅如何使用 Visual Studio Code 扩展来浏览 Azure Cosmos DB for NoSQL 数据。
清理资源
不再需要示例应用程序或资源时,请删除相应的部署和所有资源。
azd down