1
目前我正在開發可以處理事務的虛擬貨幣。我遇到的問題是我不希望一個用戶同時執行多個事務。
下面是一個例子:湯姆和比爾同時嘗試向John發送2美元。我不會同時執行transact()
函數,而是我的系統首先完成Tom的事務,然後移動到Billy等。在node.js上爲用戶排隊的一種方法
我該如何設置這樣的系統?
編輯:由於我的代碼將是開源反正這裏是我所目前做了一個例子:
//Step 0 - Transaction setup.
var transaction = {
"id": hexit(Math.random().toString().replace(".", "") +
from + to + new Date().getTime() +
Math.random().toString().replace(".", "")),
"from": from,
"to": to,
"amount": amount,
"time": new Date().getTime(),
"coins": [],
"message": validator.escape(message)
};
//LCF.getuser returns the data for the 'coins' field.
var from = LCF.getuser(from, ["coins"]);
//Amount is the amount of coins that the user wants to transact
if(from.coins.length <= amount) {
while(transaction.coins.length < amount) {
collection.update(
{ "username" : from },
{ "$pop": { "coins": 1 } }
);
}
(...)
我需要從$彈出更新的硬幣,雖然我可以嘗試並從最新的文檔和以前檢索的文檔中獲得差異,如果另一個事務正在更新時發生,那麼我無法知道已從用戶錢包中彈出的硬幣。
不是一個壞問題。也許顯示一些你迄今爲止所做的編碼。 –
@NeilLunn看到我的新編輯。 – C1D
可能有很多方法可以做到這一點,控制訪問。信號量是實現它的途徑之一,特別是在操作系統級別。碰巧,在NPM上有一個叫做信號量的包,可以幫助你。 – user602525