You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在AWS SAM项目中配置全局变量供多Lambda函数复用

问题解答

Lambda的运行环境是相互隔离的无状态容器,内存中创建的数据库连接属于单个Lambda实例的本地资源,无法跨不同的Lambda函数实例共享,因此你想要在Step Functions编排的多个Lambda函数中直接复用同一个已创建的数据库连接的需求,原生无法实现。
以下是可落地的优化方案:

  • 单Lambda实例内的连接复用:将数据库连接初始化逻辑放在handler函数外部,同一个Lambda实例冷启动后,后续的热启动调用可以直接复用已创建的连接,避免每次调用都重新建连。你当前的代码已经将连接初始化放在全局位置,已经实现了单实例内的复用。
  • 接入RDS Proxy降低连接开销:配置AWS RDS Proxy作为数据库的统一接入层,所有Lambda函数都连接到RDS Proxy,由Proxy统一池化管理底层到RDS的实际连接。这种方式下不同Lambda的连接请求会被Proxy复用真实的数据库连接,既可以大幅降低RDS的连接数压力,也能减少建连的性能损耗,是生产环境的标准解决方案。
  • 可共享资源的缓存复用:你代码中生成的RDS IAM认证token有效期为15分钟,可以将生成的token缓存在AWS Parameter Store或者ElastiCache中,其他Lambda函数可以直接读取缓存的token,无需重复调用generate_db_auth_token接口,减少不必要的API请求开销。

关联参考代码与配置

数据库连接Lambda代码(Python)

# import requests
'''
Get authetication token from RDS
'''
rds_client = boto3.client('rds')
auth_token = rds_client.generate_db_auth_token( os.environ['DB_HOST_PROD'], 3306, os.environ['DB_USER_PROD'])

logging.debug("response from generate_db_auth_token")
logging.debug(auth_token)
'''
This method will return an authentication token in the 
form of a signed url. The we will use this token to create the bd connection
'''
# construct SSL
ssl = {'ca': '/opt/python/rds-combined-ca-bundle.pem'}

# Creating connection
db_connection_dw = pymysql.connect(
    host=os.environ['DB_HOST_PROD'],
    port=3306,
    user=os.environ['DB_USER_PROD'],
    passwd=auth_token,
    db=os.environ['DB_NAME_PROD'],
    charset='utf8',
    ssl=ssl,
    connect_timeout=5)
logging.debug("SUCCESS: Connection to MySQL database succeeded")

SAM项目YAML模板配置

Parameters:
  LambdaSg:
    Description: "Lambda security group ID"
    Type: "CommaDelimitedList"
   # Type: List<AWS::EC2::SecurityGroup::Id>
  LambdaSubnets:
    Description: "Lambda subnets"
    Type: List<AWS::EC2::Subnet::Id>
  DBResourceId:
    Type: String
    Description: "RDS-DB instance resource identifier"
  DBEndpoint:
    Type: String
    Description: "Amazon RDS MySQL endpoint"
  DBName:
    Type: String
    Description: "Name of the database connected"
  DBUsername:
    Type: String 
    NoEcho: true

内容的提问来源于stack exchange,提问作者Lorena

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 22:45:01