内容简介:翻译自:https://stackoverflow.com/questions/23041800/firebase-transactions-via-rest-api
我发现事务( https://www.firebase.com/docs/transactions.html
)是处理并发的一种很酷的方式,但似乎它们只能从客户端完成.
我们使用Firebase的方式主要是从我们的服务器写入数据并在客户端上观察它们.有没有办法在通过REST API编写数据时实现乐观并发模型?
谢谢!
您可以使用更新计数器使写操作以与事务类似的方式工作. (我将在下面使用一些伪代码;对不起,但我不想写一个完整的REST 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);
}
}
翻译自:https://stackoverflow.com/questions/23041800/firebase-transactions-via-rest-api
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网
猜你喜欢:- 通过MSXSL方式进行鱼叉式网络钓鱼
- 通过nginx进行udp报文负载均衡
- 8.通过Python连接Docker进行编程
- 技术分享 | 如何通过PowerShell DSC进行横向渗透
- 【技术分享】通过短信进行XSS攻击:在Verizon Message应用中利用文本消息进行攻击
- django – Python通过访问令牌进行社交认证验证失败
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
MySQL入门很简单
黄缙华 / 清华大学出版社 / 2011-1 / 59.50元
《MySQL入门很简单》从初学者的角度出发,由浅入深,循序渐进地介绍了mysql数据库应用与开发的相关知识。书中提供了大量操作mysql数据库的示例,还提供了大量实例和上机实践内容,供读者演练。《MySQL入门很简单》附带1张dvd光盘,内容为与《MySQL入门很简单》内容完全配套的多媒体教学视频和《MySQL入门很简单》涉及的源代码。 《MySQL入门很简单》共分5篇。第1篇介绍数据库的基......一起来看看 《MySQL入门很简单》 这本书的介绍吧!