我在本地运行具有两个不同端口的相同应用程序。我提供的代码仅用于测试。这里 access_key 和 secret_key 将在后期从环境变量中提供。
当我在不同的端口上运行相同的应用程序时,我看到两者都能够获取 dynamodb 分区键中的锁。
这对我来说是全新的。如果我需要从 AWS 控制台在 AWS DynamoDB 中创建任何锁定机制,请需要您的支持。
下面是 AWS 控制台 DynamoDB 表快照和代码片段,我可以在其中看到日志:“获得锁!如果我死了,我的锁将在 10 秒后过期。” 来自两个正在运行的实例。根据我的要求,如果我从一个实例锁定,则另一个实例不应该获取锁,它应该提供日志“获取锁失败!”。
在 Spring Boot 中执行代码时也出现错误。AmazonDynamoDBLockClient:心跳线程收到中断,正在退出 run()(可能正在退出线程)
@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.");
}
}