简体   繁体   English

如何在 AWS Lambda 中访问 Elasticache 和 Internet?

[英]How to access Elasticache and Internet in AWS Lambda?

I just wrote a python script that connect to the AWS ElastiCache.我刚刚编写了一个连接到 AWS ElastiCache 的 python 脚本。 And it just check the connection.它只是检查连接。

from redis import Redis

try:
    redis = Redis(host='xxx.cache.amazonaws.com',
                  port=6379,
                  db=0)

    if not redis.ping():
        raise("REDIS can't be initialized")

    return True
except Exception as e:
    print(str(e))
    return False

When the following code is ran under my EC2 it has no problem and the response is reeally fast.当以下代码在我的 EC2 下运行时,它没有问题并且响应非常快。 Then I wrapped this using AWS Lambda and invoke the function locally.然后我使用 AWS Lambda 包装它并在本地调用该函数。 The returned result is still normal.返回的结果还是正常的。 But when the AWS Lambda is deployed on cloud the function got stuck on the redis.ping() until the function went timeout after 30 seconds.但是,当 AWS Lambda 部署在云上时,函数会卡在redis.ping()上,直到函数在 30 秒后超时。

I am not sure why the behavior is totally different.我不确定为什么行为完全不同。

Thanks in advance.提前致谢。

In a nutshell, this is what I did简而言之,这就是我所做的

  1. Follow AWS Knowledge Center Videos: How do I give internet access to my Lambda function in a VPC?关注AWS 知识中心视频:如何为 VPC 中的 Lambda 函数提供 Internet 访问权限? and created a Lambda function that would have internet access in the VPC并创建了一个可以在 VPC 中访问 Internet 的 Lambda 函数
  2. Follow Modifying a subnet group and make sure that the Redis's subnet is same as the Subnet of Lambda function按照修改子网组,确保 Redis 的子网与 Lambda 函数的子网相同

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM