SpringBoot集成Dynamo(2)demo

一、dynamo local

1、建表
aws dynamodb create-table --table-name t_user --attribute-definitions AttributeName=user_account,AttributeType=S AttributeName=user_name,AttributeType=S --key-schema AttributeName=user_account,KeyType=HASH AttributeName=user_name,KeyType=RANGE --provisioned-throughput ReadCapacityUnits=1,WriteCapacityUnits=1 --table-class STANDARD --endpoint-url http://localhost:8000

2、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>
    </properties>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>software.amazon.awssdk</groupId>
                <artifactId>bom</artifactId>
                <version>2.17.230</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <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>

        <!--dynamo v1-->
        <dependency>
            <groupId>com.amazonaws</groupId>
            <artifactId>aws-java-sdk-dynamodb</artifactId>
            <version>1.12.310</version> <!-- 请替换为合适的版本号 -->
        </dependency>

        <!--dynamo v2-->
        <dependency>
            <groupId>software.amazon.awssdk</groupId>
            <artifactId>dynamodb</artifactId>
            <version>2.20.44</version>  <!-- 请使用最新的版本 -->
        </dependency>
        <dependency>
            <groupId>software.amazon.awssdk</groupId>
            <artifactId>dynamodb-enhanced</artifactId>
            <version>2.17.123</version>
        </dependency>
        <dependency>
            <groupId>software.amazon.awssdk</groupId>
            <artifactId>kms</artifactId>
        </dependency>
        <dependency>
            <groupId>software.amazon.awssdk</groupId>
            <artifactId>dynamodb</artifactId>
        </dependency>

    </dependencies>
</project>
3、config
package com.demo.dynamo.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;

import java.net.URI;

@Configuration
public class DynamoClientConfig {

    @Bean("dynamoDbClient")
    public DynamoDbClient dynamoDbClient() {
        // 使用自定义的 Access Key 和 Secret Key
        AwsBasicCredentials credentials = AwsBasicCredentials.create(
                "wtyyA",   // 替换为你的 Access Key
                "wtyyB" // 替换为你的 Secret Key
        );
        return DynamoDbClient.builder()
                .region(Region.US_WEST_2)
                .endpointOverride(URI.create("http://localhost:8000"))
                //.credentialsProvider(DefaultCredentialsProvider.create()) // 默认凭证
                .credentialsProvider(StaticCredentialsProvider.create(credentials))
                .build();
    }

    @Bean("dynamoDbEnhancedClient")
    public DynamoDbEnhancedClient dynamoDbEnhancedClient() { // enhanced version
        DynamoDbClient dynamoDbClient = dynamoDbClient();
        return DynamoDbEnhancedClient.builder().dynamoDbClient(dynamoDbClient).build();
    }
}
4、实体
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")
    @DynamoDbPartitionKey
    public String getUserAccount() {
        return userAccount;
    }

    @DynamoDbAttribute(value = "user_name")
    @DynamoDbSortKey
    public String getUserName() {
        return userName;
    }
}
5、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 {

    @Autowired
    private 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);
    }
}
6、单元测试
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;

@SpringBootTest(classes = {DynamoApplication.class}, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@RunWith(SpringRunner.class)
public class MyTest {

    @Autowired
    private UserRepository userRepository;

    /**
     * 保存
     */
    @Test
    public void  testSave(){
        UserEntity user = UserEntity.builder()
                .userAccount("ls").userName("lisi1")
                .build();
        userRepository.saveUser(user);
    }

    /**
     * 更新
     */
    @Test
    public void  testDelete(){
        UserEntity user = UserEntity.builder()
                .userAccount("ls").userName("lisi1")
                .build();
        userRepository.delete(user);
    }
}

(1)新增:执行 testSave,查看数据生成

再执行一次,没有插入,因为account值重复了,而改成不一样的userName又可以插入了:

(2)删除:执行testDelete,执行成功

二、远程aws dynamo

1、在aws上建表

上一篇:【已解决】git push一直提示输入用户名及密码、fatal: Could not read from remote repository的问题


下一篇:第二十一章 TCP 客户端 服务器通信 - 客户端OPEN命令