Search in sources :

Example 1 with ProvisionedThroughputExceededException

use of software.amazon.awssdk.services.dynamodb.model.ProvisionedThroughputExceededException in project para by Erudika.

the class AWSDynamoUtils method batchWrite.

/**
 * Writes multiple items in batch.
 * @param items a map of tables->write requests
 * @param backoff backoff seconds
 */
protected static void batchWrite(Map<String, List<WriteRequest>> items, int backoff) {
    if (items == null || items.isEmpty()) {
        return;
    }
    try {
        logger.debug("batchWrite(): requests {}, backoff {}", items.values().iterator().next().size(), backoff);
        BatchWriteItemResponse result = getClient().batchWriteItem(b -> b.returnConsumedCapacity(ReturnConsumedCapacity.TOTAL).requestItems(items));
        if (result == null) {
            return;
        }
        logger.debug("batchWrite(): success - consumed capacity {}", result.consumedCapacity());
        if (result.unprocessedItems() != null && !result.unprocessedItems().isEmpty()) {
            Thread.sleep((long) backoff * 1000L);
            for (Map.Entry<String, List<WriteRequest>> entry : result.unprocessedItems().entrySet()) {
                logger.warn("UNPROCESSED DynamoDB write requests for keys {} in table {}!", entry.getValue().stream().map(r -> r.getValueForField(Config._KEY, String.class).orElse("")).collect(Collectors.joining(",")), entry.getKey());
            }
            batchWrite(result.unprocessedItems(), backoff * 2);
        }
    } catch (ProvisionedThroughputExceededException ex) {
        logger.warn("Write capacity exceeded for table '{}'. Retrying request in {} seconds.", items.keySet().iterator().next(), backoff);
        try {
            Thread.sleep((long) backoff * 1000L);
            // retry forever
            batchWrite(items, backoff * 2);
        } catch (InterruptedException ie) {
            logger.error(null, ie);
            Thread.currentThread().interrupt();
        }
    } catch (InterruptedException ie) {
        logger.error(null, ie);
        Thread.currentThread().interrupt();
    } catch (Exception e) {
        logger.error("Failed to execute batch write operation on table '{}'", items.keySet().iterator().next(), e);
        throwIfNecessary(e);
    }
}
Also used : List(java.util.List) LinkedList(java.util.LinkedList) BatchWriteItemResponse(software.amazon.awssdk.services.dynamodb.model.BatchWriteItemResponse) Map(java.util.Map) HashMap(java.util.HashMap) ProvisionedThroughputExceededException(software.amazon.awssdk.services.dynamodb.model.ProvisionedThroughputExceededException) ProvisionedThroughputExceededException(software.amazon.awssdk.services.dynamodb.model.ProvisionedThroughputExceededException)

Example 2 with ProvisionedThroughputExceededException

use of software.amazon.awssdk.services.dynamodb.model.ProvisionedThroughputExceededException in project para by Erudika.

the class AWSDynamoUtils method batchGet.

/**
 * Reads multiple items from DynamoDB, in batch.
 * @param <P> type of object
 * @param kna a map of row key->data
 * @param results a map of ID->ParaObject
 * @param backoff backoff seconds
 */
protected static <P extends ParaObject> void batchGet(Map<String, KeysAndAttributes> kna, Map<String, P> results, int backoff) {
    if (kna == null || kna.isEmpty() || results == null) {
        return;
    }
    try {
        BatchGetItemResponse result = getClient().batchGetItem(b -> b.returnConsumedCapacity(ReturnConsumedCapacity.TOTAL).requestItems(kna));
        if (result == null) {
            return;
        }
        List<Map<String, AttributeValue>> res = result.responses().get(kna.keySet().iterator().next());
        for (Map<String, AttributeValue> item : res) {
            P obj = fromRow(item);
            if (obj != null) {
                results.put(obj.getId(), obj);
            }
        }
        logger.debug("batchGet(): total {}, cc {}", res.size(), result.consumedCapacity());
        if (result.unprocessedKeys() != null && !result.unprocessedKeys().isEmpty()) {
            Thread.sleep((long) backoff * 1000L);
            for (Map.Entry<String, KeysAndAttributes> entry : result.unprocessedKeys().entrySet()) {
                logger.warn("UNPROCESSED DynamoDB read requests for keys {} in table {}!", entry.getValue().keys().stream().flatMap(r -> r.values().stream().map(v -> v.s())).collect(Collectors.joining(",")), entry.getKey());
            }
            batchGet(result.unprocessedKeys(), results, backoff * 2);
        }
    } catch (ProvisionedThroughputExceededException ex) {
        logger.warn("Read capacity exceeded for table '{}'. Retrying request in {} seconds.", kna.keySet().iterator().next(), backoff);
        try {
            Thread.sleep((long) backoff * 1000L);
            // retry forever
            batchGet(kna, results, backoff * 2);
        } catch (InterruptedException ie) {
            logger.error(null, ie);
            Thread.currentThread().interrupt();
        }
    } catch (InterruptedException ie) {
        logger.error(null, ie);
        Thread.currentThread().interrupt();
    } catch (Exception e) {
        logger.error("Failed to execute batch read operation on table '{}'", kna.keySet().iterator().next(), e);
    }
}
Also used : TableDescription(software.amazon.awssdk.services.dynamodb.model.TableDescription) KeysAndAttributes(software.amazon.awssdk.services.dynamodb.model.KeysAndAttributes) LoggerFactory(org.slf4j.LoggerFactory) DynamoDbAsyncClient(software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient) StringUtils(org.apache.commons.lang3.StringUtils) StreamViewType(software.amazon.awssdk.services.dynamodb.model.StreamViewType) Map(java.util.Map) GlobalSecondaryIndex(software.amazon.awssdk.services.dynamodb.model.GlobalSecondaryIndex) URI(java.net.URI) WaiterResponse(software.amazon.awssdk.core.waiters.WaiterResponse) Config(com.erudika.para.core.utils.Config) ScalarAttributeType(software.amazon.awssdk.services.dynamodb.model.ScalarAttributeType) DynamoDbClient(software.amazon.awssdk.services.dynamodb.DynamoDbClient) ParaObject(com.erudika.para.core.ParaObject) ProjectionType(software.amazon.awssdk.services.dynamodb.model.ProjectionType) ScanResponse(software.amazon.awssdk.services.dynamodb.model.ScanResponse) KeyType(software.amazon.awssdk.services.dynamodb.model.KeyType) QueryResponse(software.amazon.awssdk.services.dynamodb.model.QueryResponse) ReturnConsumedCapacity(software.amazon.awssdk.services.dynamodb.model.ReturnConsumedCapacity) Collectors(java.util.stream.Collectors) List(java.util.List) BatchGetItemResponse(software.amazon.awssdk.services.dynamodb.model.BatchGetItemResponse) Annotation(java.lang.annotation.Annotation) AttributeValue(software.amazon.awssdk.services.dynamodb.model.AttributeValue) Optional(java.util.Optional) Para(com.erudika.para.core.utils.Para) DefaultAwsRegionProviderChain(software.amazon.awssdk.regions.providers.DefaultAwsRegionProviderChain) ListTablesResponse(software.amazon.awssdk.services.dynamodb.model.ListTablesResponse) App(com.erudika.para.core.App) QueryRequest(software.amazon.awssdk.services.dynamodb.model.QueryRequest) Replica(software.amazon.awssdk.services.dynamodb.model.Replica) DescribeTableResponse(software.amazon.awssdk.services.dynamodb.model.DescribeTableResponse) ParaObjectUtils(com.erudika.para.core.utils.ParaObjectUtils) HashMap(java.util.HashMap) Pager(com.erudika.para.core.utils.Pager) StaticCredentialsProvider(software.amazon.awssdk.auth.credentials.StaticCredentialsProvider) ServiceNamespace(software.amazon.awssdk.services.applicationautoscaling.model.ServiceNamespace) ProvisionedThroughputExceededException(software.amazon.awssdk.services.dynamodb.model.ProvisionedThroughputExceededException) MetricType(software.amazon.awssdk.services.applicationautoscaling.model.MetricType) ScalableDimension(software.amazon.awssdk.services.applicationautoscaling.model.ScalableDimension) CreateTableRequest(software.amazon.awssdk.services.dynamodb.model.CreateTableRequest) ScanRequest(software.amazon.awssdk.services.dynamodb.model.ScanRequest) ApplicationAutoScalingClient(software.amazon.awssdk.services.applicationautoscaling.ApplicationAutoScalingClient) WriteRequest(software.amazon.awssdk.services.dynamodb.model.WriteRequest) LinkedList(java.util.LinkedList) Region(software.amazon.awssdk.regions.Region) GlobalSecondaryIndexDescription(software.amazon.awssdk.services.dynamodb.model.GlobalSecondaryIndexDescription) Logger(org.slf4j.Logger) AttributeDefinition(software.amazon.awssdk.services.dynamodb.model.AttributeDefinition) PolicyType(software.amazon.awssdk.services.applicationautoscaling.model.PolicyType) BatchWriteItemResponse(software.amazon.awssdk.services.dynamodb.model.BatchWriteItemResponse) ReplicaUpdate(software.amazon.awssdk.services.dynamodb.model.ReplicaUpdate) KeySchemaElement(software.amazon.awssdk.services.dynamodb.model.KeySchemaElement) BillingMode(software.amazon.awssdk.services.dynamodb.model.BillingMode) Projection(software.amazon.awssdk.services.dynamodb.model.Projection) CreateTableResponse(software.amazon.awssdk.services.dynamodb.model.CreateTableResponse) AwsBasicCredentials(software.amazon.awssdk.auth.credentials.AwsBasicCredentials) Collections(java.util.Collections) AttributeValue(software.amazon.awssdk.services.dynamodb.model.AttributeValue) KeysAndAttributes(software.amazon.awssdk.services.dynamodb.model.KeysAndAttributes) ProvisionedThroughputExceededException(software.amazon.awssdk.services.dynamodb.model.ProvisionedThroughputExceededException) BatchGetItemResponse(software.amazon.awssdk.services.dynamodb.model.BatchGetItemResponse) Map(java.util.Map) HashMap(java.util.HashMap) ProvisionedThroughputExceededException(software.amazon.awssdk.services.dynamodb.model.ProvisionedThroughputExceededException)

Aggregations

HashMap (java.util.HashMap)2 LinkedList (java.util.LinkedList)2 List (java.util.List)2 Map (java.util.Map)2 BatchWriteItemResponse (software.amazon.awssdk.services.dynamodb.model.BatchWriteItemResponse)2 App (com.erudika.para.core.App)1 ParaObject (com.erudika.para.core.ParaObject)1 Config (com.erudika.para.core.utils.Config)1 Pager (com.erudika.para.core.utils.Pager)1 Para (com.erudika.para.core.utils.Para)1 ParaObjectUtils (com.erudika.para.core.utils.ParaObjectUtils)1 Annotation (java.lang.annotation.Annotation)1 URI (java.net.URI)1 Collections (java.util.Collections)1 Optional (java.util.Optional)1 Collectors (java.util.stream.Collectors)1 StringUtils (org.apache.commons.lang3.StringUtils)1 Logger (org.slf4j.Logger)1 LoggerFactory (org.slf4j.LoggerFactory)1 AwsBasicCredentials (software.amazon.awssdk.auth.credentials.AwsBasicCredentials)1