题
我找到事务( https://www.firebase.com/docs/transactions.html )到是一种冷静的处理并发的方式,但似乎他们只能从客户完成。
我们使用firebase的方式主要是通过从我们的服务器写入数据并在客户端上观察它们。有没有办法通过REST API写入数据时实现乐观的并发模型?
谢谢!
解决方案
您可以利用更新计数器以使WRITE OPS以与事务类似的方式工作。(我将在下面使用一些伪代码;抱歉,但我不想为一个例子写出完整的休息API。)
例如,如果我有这样的对象:{
total: 100,
update_counter: 0
}
.
和类似的写规则:
{
".write": "newData.hasChild('update_counter')",
"update_counter": {
".validate": "newData.val() === data.val()+1"
}
}
.
我现在可以通过每次操作来防止在update_counter中传递并发修改。例如:
var url = 'https://<INSTANCE>.firebaseio.com/path/to/data.json';
addToTotal(url, 25, function(data) {
console.log('new total is '+data.total);
});
function addToTotal(url, amount, next) {
getCurrentValue(url, function(in) {
var data = { total: in.total+amount, update_counter: in.update_counter+1 };
setCurrentValue(ref, data, next, addToTotal.bind(null, ref, amount, next));
});
}
function getCurrentValue(url, next) {
// var data = (results of GET request to the URL)
next( data );
}
function setCurrentValue(url, data, next, retryMethod) {
// set the data with a PUT request to the URL
// if the PUT fails with 403 (permission denied) then
// we assume there was a concurrent edit and we need
// to try our pseudo-transaction again
// we have to make some assumptions that permission_denied does not
// occur for any other reasons, so we might want some extra checking, fallbacks,
// or a max number of retries here
// var statusCode = (server's response code to PUT request)
if( statusCode === 403 ) {
retryMethod();
}
else {
next(data);
}
}
. 其他提示
fyi,firebase实时数据库现在正式支持。
阅读 blog 和
检查Firebase-Transaction项目: https://github.com/vacuumlabs/firebase-transactionEtezezut
不隶属于 StackOverflow