我在我的开发机器上运行了这段代码,还有一个 Redis 实例。
if (req.url === "/get_id" && req.method === "GET") {
console.log("Requesting an id");
//Generate unique ID's until one is found and return it to the client
let currentString = "";
do {
currentString = randomString({ length: 10 });
} while (redisClient.SISMEMBER("uniqueSet", currentString) === 1);
//the above will run until currentString is unique
//add unique value to set
redisClient.sadd("uniqueSet", currentString);
console.log(currentString);
//now return to client and close
res.end(currentString);
}
它是否可以按原样与云函数一起使用,还是我需要将其重写为异步的?另外,上面的内容是否更适合应用引擎?
最佳答案
这就是我最终更改代码的方式。当我启动并测试云功能时,它起作用了,所以我假设它没问题……直到我了解其他情况。
"use strict";
//const functions = require("firebase-functions");
const randomString = require("crypto-random-string");
const redis = require("redis");
const { promisify } = require("util");
const REDISHOST = process.env.REDISHOST;
const REDISPORT = process.env.REDISPORT;
//use the unix socket option in production
const redisClient = redis.createClient(REDISPORT, REDISHOST); //unix_socket
const sismemberAsync = promisify(redisClient.sismember).bind(redisClient);
redisClient.on("error", function(err) {
return;
// but since this is an http function should I be calling res.end()?
});
//exports.my_id = functions.https.onRequest((req, res) => {
exports.my_id = (req, res) => {
async function getUnique() {
try {
//console.log("top function firing");
let currentString = randomString({ length: 10 });
let result = await sismemberAsync("uniqueSet", currentString);
//console.log(result);
// the element is unique
if (result == 0) {
//console.log("We are unique");
redisClient.sadd("uniqueSet", currentString);
res.end(currentString);
}
// the element is not unique
if (result === 1) {
//console.log("we are not unique");
getUnique(); // try again
}
// the operation failed
if (result === undefined) {
//console.log("the async operation failed");
getUnique(); // try again
//res.end();
}
} catch (error) {
res.end();
}
}
// invoke the above function
getUnique();
};
我仍然不确定的事情,以防其他人发现它有用:
如果云函数是一个 http 调用函数,调用 return 会结束它的执行,还是需要调用 res.end() 或其他 res.function()?主要是想着redis关于“error”的功能。
当我启动该功能时,我使用控制台并从下拉菜单中设置环境变量。我使用了我的 memorystore 实例中的设置(包括主机 ip 和端口),但是在设置无服务器 vpc 访问时,我设置的连接器有一个单独的 ip 地址。因此,函数如何找到我的 Redis 实例超出了我的范围,除非连接器只是将您带到 vpc,然后您可以通过列出的 ip 访问为范围内的项目运行的任何服务?
不知道设置多个连接器好不好?还是每个功能一个连接器?
我听说使用 unix 套接字是个好主意,因为它可以提高吞吐量或其他东西,但我不确定无服务器解决方案是否可行。
关于asynchronous - 我是否需要重新编写代码以使所有数据库操作异步?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56453517/