Notice
Recent Posts
Recent Comments
Link
«   2024/12   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31
Archives
Today
Total
관리 메뉴

아님말고

[AWS] DynamoDB + Spring boot 연동하기 본문

Java

[AWS] DynamoDB + Spring boot 연동하기

스타박씨 2023. 8. 3. 11:11

spring에서 aws의 DynamoDB에 저장하고 가져오는 것이 쉽지않았다. aws 가이드를 보고, 검색을 하는데 혼란스러웠던 점을 적는다면,

 

1. aws의 자격증명 방법이 여러가지이다.

더보기

-JavaA 시스템 속성 : SystemPropertyCredentialsProvider
-환경 변수 :  EnvironmentVariableCredentialsProvider
-웹 ID 토큰 출처 :  WebIdentityTokenFileCredentialsProvider
-공유 credentials 및 config 파일 : ProfileCredentialsProvider
-Amazon ECS컨테이너 자격 증명 :  ContainerCredentialsProvider
-Amazon EC2인스턴스 IAM 역할 제공 자격 증명 :  InstanceProfileCredentialsProvider

※출처 : https://docs.aws.amazon.com/ko_kr/sdk-for-java/latest/developer-guide/credentials-chain.html

 

2. dynamoDB의 SDK가 두 종류이다.

spring-data-dynamodb VS aws-java-sdk-dynamodb

나는 aws에서 직접 제공하는 AWS SDK (aws-java-sdk-dynamodb)을 이용할 것이다.

 

3. AWS SDK 는 1.x 버전과 2.x 버전으로 크게 구분 짓는데 1.x 버전과 2.x 버전은 많은 부분에서 차이점이 있다.

DynamoDBMapper VS DynamoDb Enhanced

좀 더 차이점을 알려면 :  [AWS] AWS SDK For Java 버전1과 2의 차이 (tistory.com)

 

 

AWS SDK for Java 2.x 으로 개발하기

 

의존성 추가

	implementation platform('software.amazon.awssdk:bom:2.20.85')
	implementation 'software.amazon.awssdk:dynamodb-enhanced'

 

application.properties

aws.accessKey= AKIAVB4PSXJDCXXXX
aws.secretKey= iY7Qx147FCArpempkFdOYGjDbXXXXXXXXXXXX

 

config 설정파일

@Configuration
public class DynamoDBConfiguration {

    @Value("${aws.accessKey}")
    private String accessKey;

    @Value("${aws.secretKey}")
    private String secretKey;

    @Bean
	public DynamoDbClient dynamoDbClient(){
    	return DynamoDbClient.builder()
    			.region(Region.AP_NORTHEAST_2)
    			.credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create(accessKey, secretKey)))
    			.build();
	}

	@Bean
	public DynamoDbEnhancedClient dynamoDbEnhancedClient(@Qualifier("dynamoDbClient") DynamoDbClient dynamoDbClient){
		return DynamoDbEnhancedClient.builder()
				.dynamoDbClient(dynamoDbClient)
				.build();
	}
}

 

도메인

@Builder
@DynamoDbBean
@NoArgsConstructor
@AllArgsConstructor
@Setter
public class Customer {

	@Getter(onMethod_=@DynamoDbPartitionKey)
    private String customerId;

	@Getter
    private String firstName;

	@Getter
    private String lastName;

	@Getter
    private String email;

}

 

리파지토리

@Repository
public class CustomerRepository {

	private final DynamoDbTable<Customer> customerTable;

    public CustomerRepository(@Autowired DynamoDbEnhancedClient dynamoDbEnhancedClient) {
        this.customerTable = dynamoDbEnhancedClient.table("Customer", TableSchema.fromBean(Customer.class));
    }	
	
    //저장하기
    public void saveCustomer(Customer customer) {
    	customerTable.putItem(customer);
    }

    //조회하기
    public Customer getCustomerById(String customerId) {
        return customerTable.getItem(Key.builder().partitionValue(customerId).build());
    }
    
    //수정하기
    public void updateCustomer(Customer customer) {
    	customerTable.updateItem(customer);
    }
    
    //삭제하기
    public void deleteCustomer(String customerId) {
    	customerTable.deleteItem(Key.builder().partitionValue(customerId).build());
    }

}

 

서비스

@Service
@RequiredArgsConstructor
public class CustomerService {
	
    private final CustomerRepository customerRepository;
    
    public void saveCustomer(Customer customer) {
        customerRepository.saveCustomer(customer);
    }

    public Customer getCustomerById(String customerId) {
        return customerRepository.getCustomerById(customerId);
    }
    
    public void updateCustomer(Customer customer) {
    	customerRepository.updateCustomer(customer);
    }
    
    public void deleteCustomer(String customerId) {
    	customerRepository.deleteCustomer(customerId);
    }    
}

 

Controller

@RestController
@RequiredArgsConstructor
public class CustomerController {

    private final CustomerService customerService;

    //저장하기
    @PostMapping("/customer")
    public void saveCustomer(Customer customer) {
        customerService.saveCustomer(customer);
    }

    //조회하기
    @GetMapping("/customer/{customerId}")
    public Customer getCustomerById(@PathVariable("customerId") String customerId) {
        return customerService.getCustomerById(customerId);
    }
    
    //수정하기
    @PutMapping("/customer")
    public void updateCustomer(Customer customer) {
    	customerService.updateCustomer(customer);
    }
    
    //삭제하기
    @DeleteMapping("/customer/{customerId}")
    public void deleteCustomer(@PathVariable("customerId") String customerId) {
    	customerService.deleteCustomer(customerId);
    }    
}
Comments