Amazon web services 使用DynamoDB锁的主被动应用
我有一个用例,我想在主动-被动模式下运行我的应用程序。两个实例将运行,但只有一个实例处于活动状态,首先获取锁,而另一个实例将持续等待锁 我在我的项目中使用Dynamodb表,我想基于Dynamodb实现锁。我不知道它是如何工作的Amazon web services 使用DynamoDB锁的主被动应用,amazon-web-services,locking,amazon-dynamodb,Amazon Web Services,Locking,Amazon Dynamodb,我有一个用例,我想在主动-被动模式下运行我的应用程序。两个实例将运行,但只有一个实例处于活动状态,首先获取锁,而另一个实例将持续等待锁 我在我的项目中使用Dynamodb表,我想基于Dynamodb实现锁。我不知道它是如何工作的 有人能帮助我理解如何使用dynamodb表上的锁来实现这一点吗?您所考虑的dynamodb中的功能是条件写入。DynamoDB不支持本机“锁定”,但您可以使用条件写入来实现基于租约或锁的系统,该系统应该通过使用DynamoDB实现您想要的功能 首先要决定的是,您是要实现
有人能帮助我理解如何使用dynamodb表上的锁来实现这一点吗?您所考虑的dynamodb中的功能是条件写入。DynamoDB不支持本机“锁定”,但您可以使用条件写入来实现基于租约或锁的系统,该系统应该通过使用DynamoDB实现您想要的功能 首先要决定的是,您是要实现基于租约的系统还是基于锁的系统。主要区别在于,如果租约在某个时间段内未续订,租约将自动过期,而锁将永远不会自动过期。一般来说,当使用分布式系统时,租约在大多数情况下具有更好的特性。例如,如果主节点死亡,备用节点将在租约到期时接管,但如果是锁,则在另一个系统释放锁之前,备用节点不会接管 基于锁的系统可以被视为基于租约的系统的一个特例,其中租约到期时间无限长,因此我将描述如何在DynamoDB中实现基于租约的系统
在DynamoDB中实现租赁系统的方法是创建一个表,该表将包含记录,其中每个记录表示不同的租赁。桌子的设计可以如下所示:
- leaseId(哈希键)
- resourceId(仅当租约分配给持有租约的人时设置)
- 租赁支出(仅在分配租赁时设置;租赁到期时的时间戳)
if (not holding lease) then
read record from DynamoDB using leaseId
if (resourceId is not set) then
# lease appears to be available
perform conditional write on leaseId record
# set resourceId to our ID and leaseExpiration to time in future
# with condition that resourceId and leaseExpiration are not set
if (conditional write succeeds) then
# we have the lease!
return true
else
# failed to get the lease
return false
done
else if (leaseExpiration is past)
# lease has expired so lets attempt to take it
perform conditional write on leaseId record
# set resourceId to our ID and leaseExpiration to time in future
# with condition that resourceId and leaseExpiration were values we read earlier
if (conditional write succeeds) then
# we have the lease!
return true
else
# failed to get the lease
return false
done
done
else
# we have the lease, so lets keep it
perform conditional write on leaseId record
# set leaseExpiration to time in future
# with condition that resourceId is equal to our ID
if (conditional write succeeds) then
# we still have the lease!
return true
else
# we lost our lease
return false
done
done
如果整个服务器都受到保护,那么上述算法基本上是在循环中运行的。如果资源具有租约,则需要在租约到期之前运行,以确保资源保留租约。如果资源没有租约,则应等待一段时间,然后再尝试获取租约
如果服务器想要放弃锁,那么它将执行以下算法:
perform conditional write on leaseId record
# erase resourceId and erase leaseExpiration attributes
# with condition that resourceId is equal to our ID
if (conditional write succeeds) then
# we successfully gave up the lease
else
# the lease was not ours to give up
done