按照推荐的AWS IAM SSO模式,以文件存储凭证的方式,看下代码是如何访问的。
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>org.example</groupId><artifactId>dynamo-demo</artifactId><version>1.0-SNAPSHOT</version><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>3.2.4</version><relativePath/></parent><properties><maven.compiler.source>17</maven.compiler.source><maven.compiler.target>17</maven.compiler.target><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><aws.sdk.version>2.20.4</aws.sdk.version> <!-- 请使用最新的 AWS SDK 版本 --><jackson.version>2.16.2</jackson.version></properties><repositories><repository><id>central</id><url>https://repo.maven.apache.org/maven2</url></repository></repositories><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter</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></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><scope>test</scope></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId></dependency><!-- AWS SDK for DynamoDB --><dependency><groupId>software.amazon.awssdk</groupId><artifactId>dynamodb</artifactId><version>${aws.sdk.version}</version></dependency><dependency><groupId>software.amazon.awssdk</groupId><artifactId>dynamodb-enhanced</artifactId><version>${aws.sdk.version}</version></dependency><dependency><groupId>software.amazon.awssdk</groupId><artifactId>sts</artifactId><version>${aws.sdk.version}</version></dependency><dependency><groupId>software.amazon.awssdk</groupId><artifactId>ssooidc</artifactId><version>${aws.sdk.version}</version></dependency><!-- AWS SDK Core, 必须添加 --><dependency><groupId>software.amazon.awssdk</groupId><artifactId>aws-core</artifactId><version>${aws.sdk.version}</version></dependency><!-- AWS SDK for SSO (如果需要)--><dependency><groupId>software.amazon.awssdk</groupId><artifactId>sso</artifactId><version>${aws.sdk.version}</version></dependency><!-- Logging dependencies for AWS SDK --><dependency><groupId>software.amazon.awssdk</groupId><artifactId>apache-client</artifactId><version>${aws.sdk.version}</version></dependency><dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-core</artifactId><version>${jackson.version}</version></dependency></dependencies>
</project>
在aws上建一个dynamo表:
一、配置文件法流程
1、IAM SSO凭证配置
cmd输入aws configure sso后按照提示一步步进行,最后生成了config和credentials文件。
config文件:
内容为:
[profile my-test] sso_session = sso-dev sso_account_id = ****** sso_role_name = xxxxxx region = us-east-1 output = json [sso-session sso-dev] sso_start_url = https://xxx.xxx.xx sso_region = us-east-1 sso_registration_scopes = sso:account:access
cmd输入aws cli某一个命令验证是否配置成功: 以下是获取所有表的命令
aws dynamodb list-tables --profile <your-profile-name>
如我输入:aws dynamodb list-tables --profile my-test 有内容输出,说明凭证配置成功了。
查看上面创建的表:(命令好像不对)
aws dynamodb describe-table --table-name <your-table-name> --profile <your-profile-name>
后面凭证过期了,再输入aws sso login --profile my-test 再次登录即可。
2、编码
(1)config
package com.demo.dynamo.config;import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import software.amazon.awssdk.auth.credentials.*;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;@Configuration
public class DynamoClientConfig {@Bean("dynamoDbClient")public DynamoDbClient dynamoDbClient() {AwsCredentialsProvider credentialsProvider = ProfileCredentialsProvider.create("my-test");return DynamoDbClient.builder().region(Region.US_EAST_1)//.endpointOverride(URI.create(url))//.credentialsProvider(DefaultCredentialsProvider.create()) // 默认凭证//.credentialsProvider(StaticCredentialsProvider.create(credentials))//.credentialsProvider(ProfileCredentialsProvider.create()) // 默认使用AWS CLI的配置文件.credentialsProvider(credentialsProvider).build();}@Bean("dynamoDbEnhancedClient")public DynamoDbEnhancedClient dynamoDbEnhancedClient() { // enhanced versionDynamoDbClient dynamoDbClient = dynamoDbClient();return DynamoDbEnhancedClient.builder().dynamoDbClient(dynamoDbClient).build();}
}
(2)实体
package com.demo.dynamo.entity;import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.*;
//import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTable;@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
@DynamoDbBean
//@DynamoDBTable(tableName = "t_user")
public class UserEntity {private String userAccount;private String userName;@DynamoDbAttribute(value = "user_account")@DynamoDbPartitionKeypublic String getUserAccount() {return userAccount;}@DynamoDbAttribute(value = "user_name")@DynamoDbSortKeypublic String getUserName() {return userName;}
}
(3)dao
package com.demo.dynamo.repository;import com.demo.dynamo.entity.UserEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable;
import software.amazon.awssdk.enhanced.dynamodb.Expression;
import software.amazon.awssdk.enhanced.dynamodb.TableSchema;
import software.amazon.awssdk.enhanced.dynamodb.model.PageIterable;
import software.amazon.awssdk.enhanced.dynamodb.model.QueryConditional;
import software.amazon.awssdk.enhanced.dynamodb.model.QueryEnhancedRequest;
import software.amazon.awssdk.enhanced.dynamodb.model.UpdateItemEnhancedRequest;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;import java.util.Map;@Repository
@Slf4j
public class UserRepository {@Autowiredprivate DynamoDbEnhancedClient enhancedClient;public void saveUser(UserEntity userEntity) {// 获取表格映射DynamoDbTable<UserEntity> mappedTable = enhancedClient.table("t_user", TableSchema.fromBean(UserEntity.class));// 插入数据mappedTable.putItem(userEntity);}public void delete(UserEntity userEntity) {// 获取表格映射DynamoDbTable<UserEntity> mappedTable = enhancedClient.table("t_user", TableSchema.fromBean(UserEntity.class));mappedTable.deleteItem(userEntity);}
}
(4)启动类
package com.demo.dynamo;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication
public class DynamoApplication {public static void main(String[] args) {SpringApplication.run(DynamoApplication.class, args);}
}
(5)单测
package com.demo.dynamo;
import com.demo.dynamo.entity.UserEntity;
import com.demo.dynamo.repository.UserRepository;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.ListTablesRequest;
import software.amazon.awssdk.services.dynamodb.model.ListTablesResponse;@SpringBootTest(classes = {DynamoApplication.class}, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@RunWith(SpringRunner.class)
public class MyTest {@Autowiredprivate UserRepository userRepository;@Autowiredprivate DynamoDbClient dynamoDbClient;/*** 列出所有的表*/@Testpublic void testListAllTables(){// 使用 ListTables 请求列出所有表ListTablesRequest listTablesRequest = ListTablesRequest.builder().build();ListTablesResponse listTablesResponse = dynamoDbClient.listTables(listTablesRequest);// 打印所有表名System.out.println("Tables in DynamoDB:");listTablesResponse.tableNames().forEach(System.out::println);}/*** 保存*/@Testpublic void testSave(){UserEntity user = UserEntity.builder().userAccount("zs").userName("zhangsan").build();userRepository.saveUser(user);}/*** 更新*/@Testpublic void testDelete(){UserEntity user = UserEntity.builder().userAccount("ls").userName("lisi1").build();userRepository.delete(user);}
}
测试通过,查看aws控制台验证数据写入成功
3、部署
代码部署到服务器上,凭证过期了怎么办?脚本定期刷新?