AWS Lambda和Redis

6

我正试图编写一个使用Amazon ElasticCache上的Redis的AWS Lambda函数。问题是,我无法连接到Redis。我使用类似于以下代码的代码:

'use strict'

function handler (data, context, cb) {
  const redis = require("redis")
  console.log('before client initialization')
  const client = redis.createClient({
    url: 'redis://propper-url-cache.some.0001.euw1.cache.amazonaws.com:6379',
    retry_strategy: function(options) {
      console.log(options)
      if (options.total_retry_time > 1000) {
        throw new Error('can`t connect to redis')
      }
    }
  })
  console.log('after client initialization')

  client.on("error", function (err) {
    console.log('in error')
    cb({error: err})
  });

  client.get("counter", function (err, counter) {
    console.log('counter', counter)
    if(_.isNull(counter)) {
      counter = 0
    }
    client.set('counter', counter + 1, function(err) {
      console.log(err)
      cb(null, {counter: counter})
    })
  });
}

exports.handler = handler

作为结果,我在日志中看到类似以下的内容:

15:33:41
START RequestId: d8024ec2-7f36-11e6-996c-1bfcb60572c6 Version: $LATEST

15:33:42
2016-09-20T13:33:42.632Z    d8024ec2-7f36-11e6-996c-1bfcb60572c6    before client initialization

15:33:42
2016-09-20T13:33:42.813Z    d8024ec2-7f36-11e6-996c-1bfcb60572c6    after client initialization

15:33:44
END RequestId: d8024ec2-7f36-11e6-996c-1bfcb60572c6

15:33:44
REPORT RequestId: d8024ec2-7f36-11e6-996c-1bfcb60572c6  Duration: 3002.67 ms    Billed Duration: 3000 ms Memory Size: 128 MB    Max Memory Used: 19 MB

15:33:44
2016-09-20T13:33:44.620Z d8024ec2-7f36-11e6-996c-1bfcb60572c6 Task timed out after 3.00 seconds

当我更改redis的URL为明显无意义的内容时,会出现额外的一行:
2016-09-20T13:29:42.953Z    48fcb071-7f36-11e6-bc52-c5ac58c12843    { attempt: 1, error: { [Error: Redis connection to some-url.euw1.cache.amazonaws.com:6379 failed - getaddrinfo ENOTFOUND some-url.euw1.cache.amazonaws.com some-url.euw1.cache.amazonaws.com:6379] code: 'ENOTFOUND', errno: 'ENOTFOUND', syscall: 'getaddrinfo', hostna

有什么想法吗?

1
你是否为Lambda函数启用了VPC访问? - Mark B
是的,问题出在VPC访问上。谢谢。你有什么想法为什么我的行为不同吗? - kharandziuk
1
当您尝试访问某个存在的内容,但由于不正确的VPC配置而无法访问网络时,会出现超时错误。当您尝试访问不存在的内容时,会出现“未找到”错误。 - Mark B
@MarkB 我可以请您帮忙查看一下我的另一个问题吗?https://dev59.com/tJrga4cB1Zd3GeqPuOxH? - kharandziuk
1个回答

7

您需要将Redis与Lambda放在同一个VPC中。检查安全组设置。如果您有EC2访问权限,请安装redis-cli并尝试连接Redis。如果连接成功,则Lambda Redis也将连接成功。如前所述,您需要将Lambda放在同一个VPC中。

以下是演示连接到Lambda的样板代码:

console.log('before client initialization')
const redisOptions = {
  host: 'xxxx.xxx.xxx.xxx.xxx.amazonaws.com',
  port: 6379,
}

var client =  redis.createClient(redisOptions);
console.log('after client initialization');

client.on('connect', function(result) {
  console.log('connected');
}

22
在执行任何Redis命令后,调用client.quit()非常重要。如果您不调用quit(),您的lambda函数将会超时执行。 - Anup Tilak

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接