我编写了以下 Lambda 函数:
exports.handler = (event, context, callback) => {
const redis = require('redis');
const redis_client = redis.createClient({
host: 'hostname',
port: 6379
});
redis_client.set("foo", "bar");
redis_client.get("foo", function(err, reply) {
redis_client.quit();
callback(null, reply);
});
};
这很好用。但是,我想在 Lambda 调用之间重用 Redis 连接以提高性能。从理论上讲,这可以通过将 createClient() 移到处理程序之外来实现。但是,由于“redis_client.quit()”行,该连接被终止。但是,如果我不退出客户端,Lambda 函数就会超时。
使用 AWS Lambda 时在 NodeJS 中重用 Redis 的正确方法是什么?
最佳答案
要重用 Redis 客户端连接,请将其定义为处理程序外部的全局连接。
const redis = require('redis');
const redis_client = redis.createClient({
host: 'hostname',
port: 6379
});
exports.handler = (event, context, callback) => {
redis_client.set("foo", "bar");
redis_client.get("foo", function(err, reply) {
redis_client.unref();
callback(null, reply);
});
};
关于node.js - 为 NodeJS Lambda 函数重用 Redis 连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46793670/