Sure, here’s the translation: AWS DynamoDB分区键锁在Java中的实现

huangapple go评论79阅读模式
英文:

AWS DynamoDB Partition Key Lock Implementation in Java

问题

以下是您提供的内容的翻译部分:

@Component
public class AwsDynamoDBConfiguration {

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

    /**
     * AWS 配置。
     */
    @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("开始: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。");
        // 是否创建心跳后台线程
        final boolean createHeartbeatBackgroundThread = true;
        // 构建锁客户端
        client = new AmazonDynamoDBLockClient(AmazonDynamoDBLockClientOptions.builder(dynamoDB, "tbl_test_lock")
            .withTimeUnit(TimeUnit.SECONDS).withLeaseDuration(100L).withHeartbeatPeriod(3L)
            .withCreateHeartbeatBackgroundThread(createHeartbeatBackgroundThread).build());
        logger.info("已创建 DynamoDB 客户端。");
        // 尝试在分区键 "key" 上获取锁
        lockItem = client.tryAcquireLock(AcquireLockOptions.builder("key").build());
        logger.info("尝试在 DynamoDB 上获取锁。");
        if (lockItem.isPresent()) {
            logger.info("已获取锁!如果我死了,我的锁将在 10 秒后过期。");
            logger.info("否则,我将持有锁,直到停止心跳。");
            isDynamoDBLockAccessed = true;
        } else {
            logger.info("无法获取锁!");
            isDynamoDBLockAccessed = false;
        }
        client.close();
        logger.info("结束:AWS DynamoDB lockDynamoDB");
        return isDynamoDBLockAccessed;
    }

    @PreDestroy
    public void destroy() {
        logger.info("已触发 AWS DynamoDB 回调 - @PreDestroy。");
        if (client != null && lockItem != null && lockItem.isPresent()) {
            client.releaseLock(lockItem.get());
        }
        logger.info("已释放 AWS DynamoDB 锁。");
    }
}
英文:

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)

Sure, here’s the translation:
AWS DynamoDB分区键锁在Java中的实现

@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(
&quot;https://dynamodb.us-east-1.amazonaws.com&quot;, &quot;us-east-1&quot;);
private Optional&lt;LockItem&gt; lockItem;
private AmazonDynamoDBLockClient client;
public boolean lockDynamoDB() throws InterruptedException, IOException {
logger.info(&quot;Start : AWS DynamoDB lockDynamoDB&quot;);
boolean isDynamoDBLockAccessed = false;
final AmazonDynamoDB dynamoDB = AmazonDynamoDBClientBuilder.standard()
.withEndpointConfiguration(DYNAMODB_ENDPOINT)
.withCredentials(new AWSStaticCredentialsProvider(
new BasicAWSCredentials(&quot;access_key&quot;, &quot;secret_key&quot;)))
.build();
logger.info(&quot;DynamoDB created.&quot;);
// Whether or not to create a heartbeating background thread
final boolean createHeartbeatBackgroundThread = true;
// build the lock client
client = new AmazonDynamoDBLockClient(AmazonDynamoDBLockClientOptions.builder(dynamoDB, &quot;tbl_test_lock&quot;)
.withTimeUnit(TimeUnit.SECONDS).withLeaseDuration(100L).withHeartbeatPeriod(3L)
.withCreateHeartbeatBackgroundThread(createHeartbeatBackgroundThread).build());
logger.info(&quot;DynamoDB Client created.&quot;);
// try to acquire a lock on the partition key &quot;key&quot;
lockItem = client.tryAcquireLock(AcquireLockOptions.builder(&quot;key&quot;).build());
logger.info(&quot;DynamoDB try acquire lock.&quot;);
if (lockItem.isPresent()) {
logger.info(&quot;Acquired lock! If I die, my lock will expire in 10 seconds.&quot;);
logger.info(&quot;Otherwise, I will hold it until I stop heartbeating.&quot;);
isDynamoDBLockAccessed = true;
} else {
logger.info(&quot;Failed to acquire lock!&quot;);
isDynamoDBLockAccessed = false;
}
client.close();
logger.info(&quot;End : AWS DynamoDB lockDynamoDB&quot;);
return isDynamoDBLockAccessed;
}
@PreDestroy
public void destroy() {
logger.info(&quot;AWS DynamoDB Callback triggered - @PreDestroy.&quot;);
if (client != null &amp;&amp; lockItem != null &amp;&amp; lockItem.isPresent()) {
client.releaseLock(lockItem.get());
}
logger.info(&quot;AWS DynamoDB Lock has been released.&quot;);
}
}

答案1

得分: 1

需要在条件下获取锁(client.getLock("key", Optional.empty())),并且它对我有效。

if (lockItem.isPresent()) {
client.getLock("key", Optional.empty());
logger.info("已获取锁!如果我死亡,我的锁将在 " + leaseDuration + " 秒后过期。");
logger.info("否则,我将一直持有它,直到我停止心跳。");
isDynamoDBLockAccessed = true;
} else {
logger.info("无法获取锁!");
isDynamoDBLockAccessed = false;
}

英文:

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

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

huangapple
  • 本文由 发表于 2020年5月3日 19:37:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/61573794.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定