dynamodb write
dynamodb에서 write의 경우 로우별 write와 데이터를 묶어서 write를 할 수 있는 기능이 있다.
그 중 데이터를 묶어서 write를 하는 경우를 보려고 한다.
모든 api가 그렇듯 네트워크 비용이 증가하면 그만큼 지연이 발생한다
대량건을 빠른 시간 내에 처리를 해야하는 구조라면 로우별 write 보단 bulk 별 write를 고려할 수 있다.
nosql인 dynamodb의 경우 key value 형태로 데이터가 저장되므로 aws model인 AttributeValue로 데이터를 변환하는 과정을 거쳐야 한다
AttributeValue 에는 다양한 형태가 있다
1. withS - 말 그대로 String 형태로 변환하는거로 tmp : "123" 같은 형태로 들어간다.
2. withL - List 형태로 들어간다 , tmp : 0 - "11" , 1 - "22"
3. withM -Map 형태로 들어간다 , tmp : kk , aa , cc
예를 들어보자
class AModel{
String temp;
BModel bmodel;
List<CModel> cModelList;
}
class BModel{
List<String> b;
}
class CModel{
String c;
}
위 AModel을 Attribute로 변환 하기 위해
temp 는 withS , BModel은 withM , CModel은 withL 이 필요하다
AttributeValue로 변환 후에는 이를 PutRequest에 넣어 삽입 대상을 정한다
Map<String, AttributeValue> stringAttributeValueMap;
new WriteRequest().withPutRequest(new PutRequest().withItem(stringAttributeValueMap));
bulk의 경우 25개 단위로 가능하므로 25개 단위로 partition을 분리한다.
List<List<WriteRequest>> partition = Lists.partition(writeRequestList, 24);
그 후 이를 transaction write에 넣어 write를 한다.
partition.forEach(writeRequests -> {
List<TransactWriteItem> transactWriteItems = writeRequests.stream()
.map(writeRequest->new TransactWriteItem()
.withPut(new Put()
.withTableName("대상테이블")
.withItem("bulkWriteAttributeMap")
.collect(Collectors.toList());
TransactWriteItemsRequest transactWriteItemsRequest = new TransactWriteItemsRequest()
.withTransactItems(transactWriteItems);
dynamoDB.transactWriteItems(transactWriteItemsRequest);
});
cf) bulk의 경우 update 요소만이 아닌 전체를 엎어치는 과정을 거치므로 주의하여 사용한다.