谷歌云功能+实时数据库非常慢



我正在Unity中开发一款多人移动文字游戏。 我一直在使用GameSparks作为后端,但觉得它没有给我想要的对项目的控制。环顾四周后,我决定选择Firebase。这感觉是一个很好的决定,但现在我在数据库 + 云函数方面遇到了一些严重的缓慢

游戏有一个回合制模式,你玩一个回合,当你的对手完成时收到通知。回合通过云脚本调用上传,仅包含必要的数据。然后将新的游戏状态拼凑到云脚本中,并更新游戏数据库条目(activeCasualGames/{gameId})。完成此操作后,我用有关游戏的一些基本信息更新游戏信息(activeCasualGamesInfo/{gameId})条目,然后发送云消息通知对手轮到他们了。

发送的数据只有 32 kb,并且不会对代码进行复杂的更改(请参阅下面的云函数代码)。此时,游戏的完整数据库条目最大约为 100kb,但从发送回合到在服务器上更新游戏和对手通知的时间范围从 50 秒到一分钟以上。在GameSparks上,同样的操作可能需要几秒钟。

还有其他人在Firebase上体验过这种缓慢吗?我在云脚本功能中是否犯了错误,或者这是我应该期望的性能?游戏还有一个实时模式,我还没有开始在Firebase中实现,而且由于这种滞后,我觉得它不会做得太好。

提前非常感谢!

exports.uploadCasualGameRound = functions.https.onCall(
(roundUploadData, response) => {
const roundData = JSON.parse(roundUploadData);
const updatedGameData = JSON.parse(roundData.gameData);
const updatedGameInfo = JSON.parse(roundData.gameInfo);
console.log("game data object:");
console.log(updatedGameData);
console.log("game info:");
console.log(updatedGameInfo);
const gameId = updatedGameData.gameId;
console.log("updating game with id: " + gameId);
admin
.database()
.ref("/activeCasualGames/" + gameId)
.once("value")
.then(function(snapshot: { val: any }) {
let game = snapshot.val();
console.log("old game:");
console.log(game);
const isNewGame = (game as boolean) === true;
if (isNewGame === false) {
console.log("THIS IS AN EXISTING GAME!");
} else {
console.log("THIS IS A NEW GAME!");
}
// make the end state of the currently stored TurnBasedGameData the beginning state of the uploaded one (limits the upload of data and prevents timeout errors)
if (isNewGame === true) {
updatedGameData.gameStateRoundStart.playerOneRounds =
updatedGameData.gameStateRoundEnd.playerOneRounds;
} else {
// Player one rounds are not uploaded by player two, and vice versa. Compensate for this here:
if (updatedGameData.whoseTurn === updatedGameData.playerTwoId) {
updatedGameData.gameStateRoundEnd.playerTwoRounds =
game.gameStateRoundEnd.playerTwoRounds;
} else {
updatedGameData.gameStateRoundEnd.playerOneRounds =
game.gameStateRoundEnd.playerOneRounds;
}
updatedGameData.gameStateRoundStart = game.gameStateRoundEnd;
}
game = updatedGameData;
console.log("Game after update:");
console.log(game);
// game.lastRoundFinishedDate = Date.now();
game.finalRoundWatchedByOtherPlayer = false;
admin
.database()
.ref("/activeCasualGames/" + gameId)
.set(game)
.then(() => {
updatedGameInfo.roundUploaded = true;
return admin
.database()
.ref("/activeCasualGamesInfo/" + gameId)
.set(updatedGameInfo)
.then(() => {
exports.sendOpponentFinishedCasualGameRoundMessage(gameId, updatedGameInfo.lastPlayer, updatedGameInfo.whoseTurn);
return true;
});
});
});
}
);

在使用 Firebase Cloud Function + Realtime Database 时,您必须考虑一些事项。此问题可能有助于解决无服务器性能问题,例如冷启动。另外,我认为代码本身可能会被重构以减少对实时数据库的调用,因为每个外部请求都可能需要时间。一些技巧是使用更多的本地存储资源(在内存、浏览器缓存等中)并使用一些全局变量。

最新更新