简体   繁体   中英

AWS DynamoDB Partition Key Lock Implementation in Java

I am running same application with two different ports in my local. The code I have provided is only for testing. Here access_key and secret_key will be provided from environment variables in later stage.

When I run same application in different ports, I see both are able to acquire the lock in the dynamodb partition key.

This is totally new to me. Please need your support whether I need to make any locking mechanism in AWS DynamoDB from AWS Console.

Below are the AWS Console DynamoDB table snapshot and code snippet where I can see the log: "Acquired lock, If I die. my lock will expire in 10 seconds." is coming from both the running instance, As per my requirement, if I lock from one instance. the other instance should not acquire the lock where it should provide the log "Failed to acquire lock!".

Also I am getting an error while executing the code in Spring Boot. AmazonDynamoDBLockClient: Heartbeat thread recieved interrupt, exiting run() (possibly exiting thread)

在此处输入图像描述

@Component
public class AwsDynamoDBConfiguration {

    Logger logger = LoggerFactory.getLogger(AwsDynamoDBConfiguration.class);

    /**
     * AWS configuration.
     */
    @Autowired
    private AwsConfiguration awsConfiguration;

    private static final AwsClientBuilder.EndpointConfiguration DYNAMODB_ENDPOINT = new AwsClientBuilder.EndpointConfiguration(
        "https://dynamodb.us-east-1.amazonaws.com", "us-east-1");

    private Optional<LockItem> lockItem;
    private AmazonDynamoDBLockClient client;

    public boolean lockDynamoDB() throws InterruptedException, IOException {
    logger.info("Start : AWS DynamoDB lockDynamoDB");

    boolean isDynamoDBLockAccessed = false;

    final AmazonDynamoDB dynamoDB = AmazonDynamoDBClientBuilder.standard()
        .withEndpointConfiguration(DYNAMODB_ENDPOINT)
        .withCredentials(new AWSStaticCredentialsProvider(
            new BasicAWSCredentials("access_key", "secret_key")))
        .build();

    logger.info("DynamoDB created.");
    // Whether or not to create a heartbeating background thread
    final boolean createHeartbeatBackgroundThread = true;
    // build the lock client
    client = new AmazonDynamoDBLockClient(AmazonDynamoDBLockClientOptions.builder(dynamoDB, "tbl_test_lock")
        .withTimeUnit(TimeUnit.SECONDS).withLeaseDuration(100L).withHeartbeatPeriod(3L)
        .withCreateHeartbeatBackgroundThread(createHeartbeatBackgroundThread).build());
    logger.info("DynamoDB Client created.");
    // try to acquire a lock on the partition key "key"
    lockItem = client.tryAcquireLock(AcquireLockOptions.builder("key").build());
    logger.info("DynamoDB try acquire lock.");
    if (lockItem.isPresent()) {
        logger.info("Acquired lock! If I die, my lock will expire in 10 seconds.");
        logger.info("Otherwise, I will hold it until I stop heartbeating.");
        isDynamoDBLockAccessed = true;
    } else {
        logger.info("Failed to acquire lock!");
        isDynamoDBLockAccessed = false;
    }
    client.close();
    logger.info("End : AWS DynamoDB lockDynamoDB");
    return isDynamoDBLockAccessed;
    }

    @PreDestroy
    public void destroy() {
    logger.info("AWS DynamoDB Callback triggered - @PreDestroy.");
    if (client != null && lockItem != null && lockItem.isPresent()) {
        client.releaseLock(lockItem.get());
    }
    logger.info("AWS DynamoDB Lock has been released.");
    }
}

Need to get lock (client.getLock("key", Optional.empty())) under the condition and it worked for me.

if (lockItem.isPresent()) {
            client.getLock("key", Optional.empty());
            logger.info("Acquired lock! If I die, my lock will expire in " + leaseDuration + " seconds.");
            logger.info("Otherwise, I will hold it until I stop heartbeating.");
            isDynamoDBLockAccessed = true;
} else {
            logger.info("Failed to acquire lock!");
            isDynamoDBLockAccessed = false;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM