Introduction to Spring Data Azure Cosmos DB – Spring Data Azure Cosmos DB简介

最后修改: 2020年 8月 17日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

In this tutorial, we’ll learn about Azure Cosmos DB and how we can interact with it using Spring Data.

在本教程中,我们将了解Azure Cosmos DB以及如何使用Spring Data与之互动。

2. Azure Cosmos DB

2.Azure Cosmos DB

Azure Cosmos DB is Microsoft’s globally distributed database service.

Azure Cosmos DB是微软的全球分布式数据库服务。

It’s a NoSQL database, which provides comprehensive service level agreements for throughput, latency, availability, and consistency guarantees. Also, it assures 99.999% availability for both reads and writes.

它是一个NoSQL数据库,它为吞吐量、延迟、可用性和一致性保证提供全面的服务水平协议。此外,它还保证99.999%的可用性,包括读取和写入。

Azure Cosmos DB does not give only two consistency choices i.e. either consistent or not consistent. Instead, we get five consistency choices: strong, bounded staleness, session, consistent prefix, and eventual.

Azure Cosmos DB并不是只提供两种一致性选择,即要么一致,要么不一致。相反,我们有五个一致性选择。strong, bounded staleness, session, consistent prefix, 和eventual

We can elastically scale both the throughput and storage of Azure Cosmos DB.

我们可以弹性地扩展Azure Cosmos DB的吞吐量和存储。

Additionally, it’s available in all Azure regions and offers turnkey global distribution as we can replicate our data in any Azure regions just by clicking a button. This helps us in having our data closer to our users so that we can serve their requests faster.

此外,它可以在所有Azure地区使用,并提供交钥匙的全球分布,因为我们只需点击一个按钮就可以在任何Azure地区复制我们的数据。这有助于我们让我们的数据更接近我们的用户,这样我们就可以更快地满足他们的要求。

It’s schema-agnostic as it has no schema. Furthermore, we don’t need to do any index management for Azure Cosmos Db. It automatically does indexing of data for us.

它是模式无关的 因为它没有模式。此外,我们不需要为Azure Cosmos Db做任何索引管理。它自动为我们做数据的索引。

We can work with Azure CosmosDb using different standard APIs such as SQL, MongoDB, Cassandra, etc.

我们可以使用不同的标准API与Azure CosmosDb合作,如SQL、MongoDB、Cassandra等。

3. Spring Data Azure Cosmos DB

3.Spring Data Azure Cosmos DB

Microsoft also provides a module that allows us to work with Cosmos DB using Spring Data. In the next section, we’ll see how we can use Azure Cosmos DB in a Spring Boot application.

微软还提供了一个模块,允许我们使用Spring Data与Cosmos DB合作。在下一节中,我们将看到如何在Spring Boot应用程序中使用Azure Cosmos DB。

In our example, we’ll create a Spring web application that stores a product entity in an Azure Cosmos database and performs basic CRUD operations on it. First, we need to configure an account and database in the Azure portal, following the instructions in the documentation.

在我们的示例中,我们将创建一个Spring Web应用程序,将产品实体存储在Azure Cosmos数据库中并对其执行基本的CRUD操作。首先,我们需要按照文档中的说明,在 Azure 门户中配置一个帐户和数据库。

If we don’t want to create an account on the Azure portal, Azure also provides the Azure Cosmos Emulator. Even though this doesn’t contain all the functionalities of Azure Cosmos Service and there are some differences, we can use it for local development and testing.

如果我们不想在Azure门户上创建账户,Azure还提供了Azure Cosmos模拟器。尽管这并不包含Azure Cosmos服务的所有功能,而且还有一些差异,但我们可以使用它进行本地开发和测试。

We can use the Emulator in our local environment in two ways: either by downloading the Azure Cosmos Emulator on our machine or running the Emulator on Docker for Windows.

我们可以通过两种方式在本地环境中使用模拟器:要么在我们的机器上下载Azure Cosmos模拟器,要么在Docker for Windows上运行该模拟器

We’ll choose the option to run it on Docker for Windows. Let’s pull the Docker image by running the following command:

我们将选择在Windows的Docker上运行的选项。让我们通过运行以下命令来拉动Docker镜像。

docker pull microsoft/azure-cosmosdb-emulator

Then we can run the Docker image and start the container by running the following commands:

然后我们可以运行Docker镜像,并通过运行以下命令启动容器。

set containerName=azure-cosmosdb-emulator
set hostDirectory=%LOCALAPPDATA%\azure-cosmosdb-emulator.hostd
md %hostDirectory% 2>nul
docker run --name %containerName% --memory 2GB --mount "type=bind,source=%hostDirectory%,destination=C:\CosmosDB.Emulator\bind-mount" -P --interactive --tty microsoft/azure-cosmosdb-emulator

Once we’ve configured the Azure Cosmos DB account and database in the Azure portal or in Docker, we can continue to configure it in our Spring Boot application.

一旦我们在Azure门户或Docker中配置了Azure Cosmos DB账户和数据库,我们就可以继续在Spring Boot应用程序中配置它。

4. Using Azure Cosmos DB in Spring

4.在Spring中使用Azure Cosmos DB

4.1. Configuring Spring Data Azure Cosmos DB with Spring

4.1.用Spring配置Spring Data Azure Cosmos DB

We start by adding the spring-data-cosmosdb dependency in our pom.xml:

我们首先在我们的 pom.xml中添加spring-data-cosmosdb依赖项。

<dependency> 
    <groupId>com.microsoft.azure</groupId> 
    <artifactId>spring-data-cosmosdb</artifactId> 
    <version>2.3.0</version> 
</dependency>

To access Azure Cosmos DB from our Spring application we’ll need the URI of our database, it’s access keys and database name.  Then we’all add the connection properties in our application.properties:

为了从我们的 Spring 应用程序中访问 Azure Cosmos DB,我们需要数据库的 URI,它的 访问键和数据库名称。然后我们在 application.properties 中添加连接属性。

azure.cosmosdb.uri=cosmodb-uri
azure.cosmosdb.key=cosmodb-primary-key
azure.cosmosdb.secondaryKey=cosmodb-secondary-key
azure.cosmosdb.database=cosmodb-name

We can find the values of the above properties from the Azure portal. The URI, primary key, and the secondary key will be available in the keys section of our Azure Cosmos DB in the Azure portal.

我们可以从Azure门户中找到上述属性的值。URI、主键和次键将在Azure门户中我们的Azure Cosmos DB的键部分提供。

To connect to Azure Cosmos DB from our application we need to create a client. For that, we need to extend AbstractCosmosConfiguration class in our configuration class and add the @EnableCosmosRepositories annotation.

为了从我们的应用程序连接到Azure Cosmos DB,我们需要创建一个客户端。为此,我们需要在配置类中扩展AbstractCosmosConfiguration类,并添加@EnableCosmosRepositories注释。

This annotation will scan for interfaces that extend Spring Data’s repository interfaces in the specified package.

该注解将扫描指定包中扩展Spring Data的存储库接口的接口。

We also need to configure a bean of type CosmosDBConfig:

我们还需要配置一个CosmosDBConfig类型的bean。

@Configuration
@EnableCosmosRepositories(basePackages = "com.baeldung.spring.data.cosmosdb.repository")
public class AzureCosmosDbConfiguration extends AbstractCosmosConfiguration {

    @Value("${azure.cosmosdb.uri}")
    private String uri;

    @Value("${azure.cosmosdb.key}")
    private String key;

    @Value("${azure.cosmosdb.database}")
    private String dbName;

    private CosmosKeyCredential cosmosKeyCredential;

    @Bean
    public CosmosDBConfig getConfig() {
        this.cosmosKeyCredential = new CosmosKeyCredential(key);
        CosmosDBConfig cosmosdbConfig = CosmosDBConfig.builder(uri, this.cosmosKeyCredential, dbName)
            .build();
        return cosmosdbConfig;
    }
}

4.2. Creating an Entity for Azure Cosmos DB

4.2.为Azure Cosmos DB创建一个实体

In order to interact with Azure Cosmos DB, we make use of entities. So, let’s create an entity that we will store in Azure Cosmos DB. To make our Product class an entity, we’ll use the @Document annotation:

为了与Azure Cosmos DB互动,我们利用了实体。因此,让我们创建一个实体,并将其存储在Azure Cosmos DB中。为了使我们的Product类成为实体,我们将使用@Document注解:

@Document(collection = "products")
public class Product {

    @Id
    private String productid;

    private String productName;

    private double price;

    @PartitionKey
    private String productCategory;
}

In this example, we’ve used the collection attribute with the value products, to indicate this will be the name of our container in the database. If we don’t provide any value for the collection parameter, then the class name will be used as the container name in the database.

在这个例子中,我们使用了collection属性,其值为products,以表明这将是我们在数据库中的容器的名称。如果我们不为collection参数提供任何值,那么类名将被用作数据库中的容器名。

We’ve also defined an id for our document. We can either create a field with the name id in our class or we can annotate a field with the @Id annotation. Here we have used the productid field as the document id.

我们还为我们的文档定义了一个id。我们可以在我们的类中创建一个名字为id的字段,或者我们可以用@Id注解一个字段。这里我们使用了productid字段作为文档的id。

We can logically partition our data in our container by using a partition key by annotating a field with @PartitionKey. In our class, we’ve used the productCategory field as the partition key.

我们可以通过使用分区键对容器中的数据进行逻辑分区,方法是用@PartitionKey来注释一个字段。在我们的类中,我们使用了productCategory字段作为分区键。

By default, the indexing policy is defined by Azure, but we can also customize it by using @DocumentIndexingPolicy annotation on our entity Class.

默认情况下,索引策略是由Azure定义的,但我们也可以通过在实体Class上使用@DocumentIndexingPolicy annotation来定制它。

We can also enable Optimistic locking for our entity container by creating a field named _etag and annotating it with @Version.

我们还可以通过创建一个名为_etag的字段并以@Version.作为注释,为我们的实体容器启用优化锁定。

4.3. Defining the Repository

4.3.定义存储库

Now let’s create a ProductRepository interface that extends CosmosRepository. Using this interface, we can perform CRUD operations on our Azure Cosmos DB:

现在让我们创建一个ProductRepository接口,该接口扩展了CosmosRepository。使用这个接口,我们可以对Azure Cosmos DB进行CRUD操作。

@Repository
public interface ProductRepository extends CosmosRepository<Product, String> {
    List findByProductName(String productName);

}

As we can see, this is defined in a similar way to other Spring Data modules.

我们可以看到,这是以类似于其他Spring Data模块的方式定义的。

4.4. Testing the Connection

4.4.测试连接

Now we can create a Junit Test to save a Product entity in Azure Cosmos DB using our ProductRepository:

现在我们可以创建一个Junit测试,使用我们的ProductRepository在Azure Cosmos DB中保存一个Product实体。

@SpringBootTest
public class AzureCosmosDbApplicationManualTest {

    @Autowired
    ProductRepository productRepository;

    @Test
    public void givenProductIsCreated_whenCallFindById_thenProductIsFound() {
        Product product = new Product();
        product.setProductid("1001");
        product.setProductCategory("Shirt");
        product.setPrice(110.0);
        product.setProductName("Blue Shirt");

        productRepository.save(product);
        Product retrievedProduct = productRepository.findById("1001", new PartitionKey("Shirt"))
            .orElse(null);
        Assert.notNull(retrievedProduct, "Retrieved Product is Null");
    }

}

By running this Junit test we can test our connection with Azure Cosmos DB from our Spring application.

通过运行这个Junit测试,我们可以测试我们的Spring应用程序与Azure Cosmos DB的连接。

5. Conclusion

5.总结

In this tutorial, we learned about Azure Cosmos DB. Further, we learned how to access Azure Cosmos DB from a Spring Boot application, how to create entities and configure a Repository by extending CosmosRepository to interact with it.

在本教程中,我们了解了Azure Cosmos DB。此外,我们还学习了如何从Spring Boot应用程序中访问Azure Cosmos DB,如何通过扩展CosmosRepository来创建实体和配置Repository,以便与之互动。

The code for the above example is available over on GitHub.

上述例子的代码可以在GitHub上找到