AWSCDK:共享Lambda函数在堆栈之间不起作用
创始人
2024-09-24 03:30:58
0

使用 AWS CDK 创建多个堆栈时,可能需要在这些堆栈之间共享 Lambda 函数。然而,在尝试共享 Lambda 函数时,您可能会遇到问题。目前,AWS CDK 不支持将同一个 Lambda 函数添加到多个堆栈中的 CloudFormation 模板。

解决方法是将 Lambda 函数作为构造函数的参数传递给堆栈。这相当于在不同的堆栈中创建两个 Lambda 函数,然后将它们合并成一个。

下面是一个包含共享Lambda函数的AWS CDK TypeScript示例(注意:该代码片段需要aws-cdk-lib和aws-cdk-lib-lambda包):

import * as cdk from 'aws-cdk-lib';
import * as lambda from 'aws-cdk-lib/aws-lambda';
import * as s3 from 'aws-cdk-lib/aws-s3';
import * as sns from 'aws-cdk-lib/aws-sns';
import * as snsSubs from 'aws-cdk-lib/aws-sns-subscriptions';
import * as sqs from 'aws-cdk-lib/aws-sqs';

export class SharedLambdaStack extends cdk.Stack {
  public readonly sharedFunction: lambda.Function;

  constructor(scope: cdk.Construct, id: string, props?: cdk.StackProps) {
    super(scope, id, props);

    // Create the shared Lambda function
    this.sharedFunction = new lambda.Function(this, 'SharedFunction', {
      runtime: lambda.Runtime.NODEJS_14_X,
      handler: 'index.handler',
      code: lambda.Code.fromAsset(`${__dirname}/shared-lambda`),
      memorySize: 256,
      timeout: cdk.Duration.seconds(30),
    });
  }
}

interface SqsS3StackProps extends cdk.StackProps {
  readonly sharedFunction: lambda.Function;
}

export class SqsS3Stack extends cdk.Stack {
  constructor(scope: cdk.Construct, id: string, props: SqsS3StackProps) {
    super(scope, id, props);

    // Create an S3 bucket
    const bucket = new s3.Bucket(this, 'Bucket');

    // Create an SNS topic
    const topic = new sns.Topic(this, 'Topic');

    // Subscribe an SNS topic to the shared Lambda function
    topic.addSubscription(new snsSubs.LambdaSubscription(props.sharedFunction));

    // Create an SQS queue
    const queue = new sqs.Queue(this, 'Queue');

    // Subscribe an SQS queue to the shared Lambda function
    props.sharedFunction.addEventSource

相关内容

热门资讯

关于!微信微乐自建房辅助工具,... 关于!微信微乐自建房辅助工具,微乐家乡麻将自建房辅助app(开挂自建房)方法1)微乐家乡麻将自建房辅...
大家学习交流!微信卡五星辅助器... 大家学习交流!微信卡五星辅助器,微乐小程序免费黑科技(开挂自建房)方法1、很好的工具软件,可以解锁游...
三分钟了解!微乐微信自建房辅助... 三分钟了解!微乐微信自建房辅助工具插件,微乐家乡麻将自建房辅助app(开挂自建房)工具1、三分钟了解...
一分钟教会你!微乐家乡麻将自建... 一分钟教会你!微乐家乡麻将自建房辅助app,微乐自建房脚本免费入口(开挂自建房)方法1、用户打开应用...
分享实测!微信微乐自建房辅助工... 分享实测!微信微乐自建房辅助工具,微乐自建房脚本免费入口(开挂自建房)器1、起透看视 微信微乐自建房...
重大通报!微乐自建房辅助工具脚... 重大通报!微乐自建房辅助工具脚本,微乐小程序免费黑科技(开挂自建房)app微乐自建房辅助工具脚本破解...
如何分辨真伪!微乐微信自建房辅... 如何分辨真伪!微乐微信自建房辅助工具插件,微乐小程序免费黑科技(开挂自建房)技巧1、微乐微信自建房辅...
我来教教你!微乐自建房辅助工具... 我来教教你!微乐自建房辅助工具挂,微乐家乡麻将自建房辅助app(开挂自建房)工具1、玩家可以在微乐家...
重大来袭!微乐自建房辅助工具神... 重大来袭!微乐自建房辅助工具神器,微乐小程序免费黑科技(开挂自建房)器1、游戏颠覆性的策略玩法,独创...
带你了解!微信卡五星辅助器,微... 带你了解!微信卡五星辅助器,微乐自建房脚本免费入口(开挂自建房)方法1、带你了解!微信卡五星辅助器,...