小编Pat*_*man的帖子

Google Cloud Functions 实现互斥的模式是什么

我正在使用 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);
        });
}
Run Code Online (Sandbox Code Playgroud)

google-cloud-platform google-cloud-functions

5
推荐指数
1
解决办法
1823
查看次数