【发布时间】:2019-04-14 18:35:21
【问题描述】:
我正在使用 https 触发的 Google Cloud Functions 来处理客户端请求以执行数据库写入。数据的结构方式使得大多数并行写入不会导致损坏。
在少数情况下,我需要防止同一项目同时发生多个写入操作。在功能级别上锁定对某些资源的访问的常见模式是什么。我正在寻找一些“类似互斥锁”的功能。
我在考虑一些外部服务,可以授予或拒绝对资源的访问以请求函数实例,但连接开销会很大 - 每次握手等等。
根据要求添加了一个示例。在这种特定情况下,重组数据以跟踪更新并不是一个合适的解决方案。
import * as admin from "firebase-admin";
function updateUserState(userId: string) {
// Query current state
admin
.database()
.ref()
.child(`/users/${userId}/state`)
.once("value")
.then(snapshot => {
return snapshot.val() || 0;
})
.then(currentState =>
// Perform some operation
modifyStateAsync(currentState)
)
.then(newState => {
admin
.database()
.ref()
.child(`/users/${userId}/state`)
.set(newState);
});
}
【问题讨论】:
-
这听起来像XY problem。如果您显示重现实际问题的最少代码,则更有可能有人可以帮助您解决具体问题。
-
应要求添加了更具体的示例。
-
如果要基于现有值写入新值,请使用transaction。除此之外:最后两个
then()子句不返回任何值,因此如果您在 Cloud Functions 中运行此代码,它无法知道您何时完成对数据库的写入。
标签: google-cloud-platform google-cloud-functions