DynamoDB in a Spring Boot Application Using Spring Data – 在Spring Boot应用中使用Spring Data的DynamoDB

最后修改: 2016年 10月 31日

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

1. Overview

1.概述

In this article, we’ll explore the basics of integrating DynamoDB into a Spring Boot Application with a hands-on, practical example project.

在本文中,我们将通过一个实践性强的实例项目来探讨将DynamoDB集成到Spring Boot应用中的基本知识

We’ll demonstrate how to configure an application to use a local DynamoDB instance using Spring Data. We’ll also create an example data model and repository class as well as perform actual database operations using an integration test.

我们将演示如何使用Spring Data配置一个应用程序来使用本地DynamoDB实例。我们还将创建一个数据模型和存储库类的例子,并使用集成测试执行实际的数据库操作。

2. DynamoDB

2.DynamoDB

DynamoDB is a fully-managed hosted NoSQL database on AWS, similar to other NoSQL databases such as Cassandra or MongoDB. DynamoDB offers fast, consistent and predictable performance and is massively scalable.

DynamoDB是AWS上一个完全管理的托管NoSQL数据库,类似于其他NoSQL数据库,如Cassandra或MongoDB。DynamoDB提供快速、一致和可预测的性能,并具有巨大的可扩展性。

You can learn more about DynamoDB on the AWS Documentation.

您可以在AWS 文档上了解有关DynamoDB的更多信息。

Let’s install a local instance of DynamoDB to avoid incurring the cost of running a live instance.

让我们安装一个DynamoDB的本地实例,以避免产生运行实时实例的成本。

For development, running DynamoDB locally makes more sense than running on AWS; the local instance will be run as an executable JAR file.

对于开发来说,在本地运行DynamoDB比在AWS上运行更有意义;本地实例将作为一个可执行的JAR文件运行。

You can find instructions on how to run DynamoDB locally here.

您可以在这里找到关于如何在本地运行DynamoDB的说明。

3. Maven Dependencies

3.Maven的依赖性

Add the following dependencies to start working with DynamoDB using Spring Data:

添加以下依赖项,以开始使用Spring Data的DynamoDB工作。

<dependencyManagement>
    <dependencies>
    <dependency>
        <groupId>org.springframework.data</groupId>
        <artifactId>spring-data-releasetrain</artifactId>
        <version>Lovelace-SR16</version>
        <type>pom</type>
        <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>
<dependencies>
    <dependency>
        <groupId>com.amazonaws</groupId>
        <artifactId>aws-java-sdk-dynamodb</artifactId>
        <version>1.11.64</version>
    </dependency>
    <dependency>
        <groupId>com.github.derjust</groupId>
        <artifactId>spring-data-dynamodb</artifactId>
        <version>5.1.0</version>
    </dependency>
</dependencies>

Check out Spring Data Release TrainAWS Java SDK For Amazon DynamoDB, and Spring Data DynamoDB for the latest versions of the above.

查看Spring Data Release Train, AWS Java SDK For Amazon DynamoDB,以及Spring Data DynamoDB的上述最新版本。

4. Configuration

4.配置

Next, let’s define the following properties in the application.properties file:

接下来,让我们在application.properties文件中定义以下属性。

amazon.dynamodb.endpoint=http://localhost:8000/
amazon.aws.accesskey=key
amazon.aws.secretkey=key2

The access and secret keys listed above are just arbitrary values for your local config. When accessing a local instance of DynamoDB these fields need to be populated by some values but are not needed to actually authenticate.

上面列出的访问和秘密密钥只是你本地配置的任意值。当访问DynamoDB的本地实例时,这些字段需要填入一些值,但不需要实际验证。

The properties will be dynamically pulled out of the application.properties file in the Spring config:

The properties will be dynamically pulled out of the application.properties file in the Spring config:

@Configuration
@EnableDynamoDBRepositories
  (basePackages = "com.baeldung.spring.data.dynamodb.repositories")
public class DynamoDBConfig {

    @Value("${amazon.dynamodb.endpoint}")
    private String amazonDynamoDBEndpoint;

    @Value("${amazon.aws.accesskey}")
    private String amazonAWSAccessKey;

    @Value("${amazon.aws.secretkey}")
    private String amazonAWSSecretKey;

    @Bean
    public AmazonDynamoDB amazonDynamoDB() {
        AmazonDynamoDB amazonDynamoDB 
          = new AmazonDynamoDBClient(amazonAWSCredentials());
        
        if (!StringUtils.isEmpty(amazonDynamoDBEndpoint)) {
            amazonDynamoDB.setEndpoint(amazonDynamoDBEndpoint);
        }
        
        return amazonDynamoDB;
    }

    @Bean
    public AWSCredentials amazonAWSCredentials() {
        return new BasicAWSCredentials(
          amazonAWSAccessKey, amazonAWSSecretKey);
    }
}

5. The Data Model

5.数据模型

Let’s now create a POJO model to represent the data stored in DynamoDB.

现在让我们创建一个POJO模型来表示存储在DynamoDB中的数据。

This POJO will use annotations similar to those used in Hibernate to define the table name, attributes, keys and other aspects of the table.

这个POJO将使用类似于Hibernate中的注解来定义表名、属性、键和表的其他方面。

5.1. Data Model Attributes

5.1.数据模型的属性

The following class, ProductInfo, represents a table with items that contains 3 attributes:

下面这个类,ProductInfo,表示一个包含3个属性的项目表。

  1. ID
  2. MSRP
  3. Cost

5.2. Java Data Model Class

5.2.Java数据模型类

Let’s create a file called ProductInfo.java in your data model folder:

让我们在你的数据模型文件夹中创建一个名为ProductInfo.java的文件。

@DynamoDBTable(tableName = "ProductInfo")
public class ProductInfo {
    private String id;
    private String msrp;
    private String cost;

    @DynamoDBHashKey
    @DynamoDBAutoGeneratedKey
    public String getId() {
        return id;
    }

    @DynamoDBAttribute
    public String getMsrp() {
        return msrp;
    }

    @DynamoDBAttribute
    public String getCost() {
        return cost;
    }

    // standard setters/constructors
}

6. CRUD Repository

6.CRUD存储库

Next, we need to create a ProductRepository interface to define the CRUD functionality we want to build out. Repositories used to read and persist data to and from DynamoDB will implement this interface:

接下来,我们需要创建一个ProductRepository接口来定义我们要建立的CRUD功能。用于向DynamoDB读取和持久化数据的存储库将实现这个接口。

@EnableScan
public interface ProductInfoRepository extends 
  CrudRepository<ProductInfo, String> {
    
    Optional<ProductInfo> findById(String id);
}

7. Integration Test

7.集成测试

Next, let’s create an integration test to ensure we can successfully connect to the local instance of DynamoDB:

接下来,让我们创建一个集成测试,以确保我们能够成功连接到DynamoDB的本地实例。

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = Application.class)
@WebAppConfiguration
@ActiveProfiles("local")
@TestPropertySource(properties = { 
  "amazon.dynamodb.endpoint=http://localhost:8000/", 
  "amazon.aws.accesskey=test1", 
  "amazon.aws.secretkey=test231" })
public class ProductInfoRepositoryIntegrationTest {

    private DynamoDBMapper dynamoDBMapper;

    @Autowired
    private AmazonDynamoDB amazonDynamoDB;

    @Autowired
    ProductInfoRepository repository;

    private static final String EXPECTED_COST = "20";
    private static final String EXPECTED_PRICE = "50";

    @Before
    public void setup() throws Exception {
        dynamoDBMapper = new DynamoDBMapper(amazonDynamoDB);
        
        CreateTableRequest tableRequest = dynamoDBMapper
          .generateCreateTableRequest(ProductInfo.class);
        tableRequest.setProvisionedThroughput(
          new ProvisionedThroughput(1L, 1L));
        amazonDynamoDB.createTable(tableRequest);
        
        //...

        dynamoDBMapper.batchDelete(
          (List<ProductInfo>)repository.findAll());
    }

    @Test
    public void givenItemWithExpectedCost_whenRunFindAll_thenItemIsFound() { 
        ProductInfo productInfo = new ProductInfo(EXPECTED_COST, EXPECTED_PRICE);
        repository.save(productInfo); 
        List<ProductInfo> result = (List<ProductInfo>) repository.findAll();

        assertThat(result.size(), is(greaterThan(0)));
        assertThat(result.get(0).getCost(), is(equalTo(EXPECTED_COST))); 
    }
}

8. Conclusion

8.结论

And we’re done – we can now connect to DynamoDB from a Spring Boot Application.

我们已经完成了 – 我们现在可以从Spring Boot应用程序连接到DynamoDB

Of course, after completing testing locally, we should be able to transparently use a live instance of DynamoDB on AWS and run the deployed code with only minor configuration changes.

当然,在本地完成测试后,我们应该能够透明地使用AWS上的DynamoDB的实时实例,并运行部署的代码,只需稍作配置修改。

As always, the example used in this article is available as a sample project over on GitHub.

一如既往,本文中所使用的示例可作为样本项目在GitHub上获得。