代码示例:使用 Spring Boot、Amazon DynamoDB 和适用于 Java 的 AWS 开发工具包 2.x 创建您的首个 Web 应用程序
1. 介绍
这个示例可以从 web 页面提交数据到 AWS DynamoDB。除了使用 AWS DynamoDB,应用还使用了 AWS Simple Notification Service and AWS Elastic Beanstalk.
应用使用 software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient 类来存储数据到 AWS DynamoDB。(DynamoDB enhanced client)
DynamoDB 中的数据更新之后,应用会使用 AWS SNS 发送消息通知用户。
浏览器访问 web 页面,填写数据;
提交数据后,经过 Spring Controller 将数据据持久化到 DynamoDB 中的 Greeting 表;
数据表更新后,会发送一条消息通知用户(由于 SNS 服务发送短信到美国之外的国家是收费服务,所以将此功能注释了);
项目基于 Spring Boot 开发,然后使用 AWS Elastic Beanstalk 部署;
2. 创建项目
在 IntelliJ 中创建一个 Maven 项目。
3. 添加 POM 依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>spring-aws</groupId>
<artifactId>greetings</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.5.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>software.amazon.awssdk</groupId>
<artifactId>bom</artifactId>
<version>2.10.54</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- AWS API -->
<dependency>
<groupId>software.amazon.awssdk</groupId>
<artifactId>dynamodb-enhanced</artifactId>
<version>2.11.0-PREVIEW</version>
</dependency>
<dependency>
<groupId>software.amazon.awssdk</groupId>
<artifactId>dynamodb</artifactId>
<version>2.5.10</version>
</dependency>
<dependency>
<groupId>software.amazon.awssdk</groupId>
<artifactId>sns</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
4. 项目代码
- 后端代码:
- DynamoDBEnhanced:它使用 DynamoDB 增强的客户端 API 向 DynamoDB 表注入数据。
- PublishTextSMS :一个发送文本消息的 Java 类。
- Greeting:数据实体类。
- GreetingController:控制器。
- GreetingApplication:SpringBoot 入口类。
- 前端代码:
6. 创建 DynamoDB table
除了可以在 DynamoDB 控制台创建表,还可以使用代码调用 API 进行创建(Amazon DynamoDB Java code examples)