Spring 集成
AWS SDK v2、DynamoDbTemplate 概念。
30 分钟
Spring 集成
在 spring-boot-essentials 项目中用 AWS SDK v2 for Java 访问 DynamoDB。Spring 无官方 DynamoDB Starter,常用 Enhanced Client 或社区 DynamoDbTemplate 模式。
学习目标
- 添加 SDK v2 依赖并配置 Region/凭证
- 定义
@DynamoDbBean实体与 Repository 风格访问 - 理解与 JPA/MySQL 双数据源并存策略
核心内容
依赖
<dependency>
<groupId>software.amazon.awssdk</groupId>
<artifactId>dynamodb-enhanced</artifactId>
</dependency>
凭证:EC2/ECS 用 IAM Role;本地 aws configure(aws-essentials)。
配置 Bean
@Configuration
public class DynamoDbConfig {
@Bean
DynamoDbClient dynamoDbClient() {
return DynamoDbClient.builder()
.region(Region.AP_SOUTHEAST_1)
.build();
}
@Bean
DynamoDbEnhancedClient enhancedClient(DynamoDbClient client) {
return DynamoDbEnhancedClient.builder()
.dynamoDbClient(client)
.build();
}
}
实验 profile 使用 application-lab.yml,不替换 spring.datasource.url(MySQL 主库)。
Repository 风格
@Service
public class UserProgressStore {
private final DynamoDbTable<UserProgress> table;
public UserProgressStore(DynamoDbEnhancedClient enhanced) {
this.table = enhanced.table("CodeRoadMapLab-UserProgress",
TableSchema.fromBean(UserProgress.class));
}
public void save(UserProgress p) { table.putItem(p); }
public UserProgress get(String pk, String sk) {
return table.getItem(Key.builder().partitionValue(pk).sortValue(sk).build());
}
}
对照 mongo-spring:MongoRepository vs 手写 DynamoDbTable。
双数据源策略
MySQL(JPA) → cf_track、cf_lesson、用户订单等权威数据
DynamoDB → UserProgress 实验、高并发会话、Serverless 侧车
避免同一业务实体双写;跨库用 Streams 或消息队列最终一致。
练习
- 新建
UserProgressBean 与 Store,lab profile 启动验证