基本上你需要的是一个分布式锁定机制。许多分布式服务器应用程序都提供了这样的功能。
基本上,如果我们将您的问题转换为代码,它将如下所示
// BANK WITHDRAWAL APPLICATION
// Fetch BankAccount object from NCache
BankAccount account = cache.Get("Key") as BankAccount; // balance = 30,000
Money withdrawAmount = 15000;
if (account != null && account.IsActive)
{
// Withdraw money and reduce the balance
account.Balance -= withdrawAmount;
// Update cache with new balance = 15,000
cache.Insert("Key", account);
}
==========================
// BANK DEPOSIT APPLICATION
// Fetch BankAccount object from NCache
BankAccount account = cache.Get("Key") as BankAccount; // balance = 30,000
Money depositAmount = 5000;
if (account != null && account.IsActive)
{
// Deposit money and increment the balance
account.Balance += depositAmount;
// Update cache with new balance = 35,000
cache.Insert("Key", account);
}
这基本上是竞争条件的一个例子
竞争条件是两个或多个用户尝试同时访问和更改相同的共享数据,但最终以错误的顺序进行。
上述分布式锁定代码的答案是
LockHandle lockHandle = new LockHandle();
// Specify time span of 10 sec for which the item remains locked
// NCache will auto release the lock after 10 seconds.
TimeSpan lockSpan = new TimeSpan(0, 0, 10);
try
{
// If item fetch is successful, lockHandle object will be populated
// The lockHandle object will be used to unlock the cache item
// acquireLock should be true if you want to acquire to the lock.
// If item does not exists, account will be null
BankAccount account = cache.Get(key, lockSpan,
ref lockHandle, acquireLock) as BankAccount;
// Lock acquired otherwise it will throw LockingException exception
if(account != null && account.IsActive)
{
// Withdraw money or Deposit
account.Balance += withdrawAmount;
// account.Balance -= depositAmount;
// Insert the data in the cache and release the lock simultaneously
// LockHandle initially used to lock the item must be provided
// releaseLock should be true to release the lock, otherwise false
cache.Insert("Key", account, lockHandle, releaseLock);
}
else
{
// Either does not exist or unable to cast
// Explicitly release the lock in case of errors
cache.Unlock("Key", lockHandle);
}
}
catch(LockingException lockException)
{
// Lock couldn't be acquired
// Wait and try again
}
这个答案非常特定于 NCache(分布式缓存)。我相信您会在关键字“分布式锁定”下找到更多解决方案
资源