AWS CDK 与 AWS Amplify

P-M*_*ing 6 amazon-web-services aws-amplify aws-cdk

我对 AWS Amplify 和 CDK 有疑问。在 Amplify 中,我们是否可以创建新环境并将它们发布到各自的存储桶中?为什么我们需要CDK?有什么用例可以让 CDK 更适合吗?

ale*_*avi 3

CDK 允许您部署(相当)任何类型的堆栈,您必须使用 cloudformation 手动完成。使用cdk,您将更快速、更安全地创建 CloudFormation 堆栈。

以JAVA为例,为了创建一个新的Table,你可以使用下面的代码来代替处理YAML配置:

 private Table CreateMasterDataTable(String TABLE_NAME) {
    return Table.Builder.create(this, TABLE_NAME + "_MasterDataTable")
            .tableName(TABLE_NAME.concat("_gvr-bic-masterdata"))
            .partitionKey(Attribute.builder().type(AttributeType.STRING).name("siteId").build())
            .removalPolicy(RemovalPolicy.RETAIN)
            .stream(StreamViewType.NEW_AND_OLD_IMAGES)
            .readCapacity(5)
            .writeCapacity(5)
            .build();
}
Run Code Online (Sandbox Code Playgroud)

为了创建一个新的 Lambda(提供一个已经存在的 JAR),您可以使用以下代码而不是处理 YAML 配置:

private Function CreateSiteAggregationNowFunction() {
    Map<String, String> env = new HashMap<>();
    env.put(Constants.LAMBDA_KEY_ENV, API_NAME);
    return Function.Builder.create(this, API_NAME + "_SiteAggregationNow")
            .code(Code.fromAsset(Constants.LAMBDA_PATH_SITE_NOW))
            .handler("it.fabricalab.gvr.bic.DeviceLoader::handleRequest")
            .timeout(Duration.seconds(30))
            .environment(env)
            .functionName(API_NAME.concat("_SiteAggregationNow"))
            .runtime(Runtime.JAVA_8)
            .retryAttempts(Constants.LAMBDA_RETRY_FALLBACK)
            .memorySize(512)
            .build();
}
Run Code Online (Sandbox Code Playgroud)

然后,为了创建让 lambda 从表中读取的策略:

final Table masterDataTable = CreateMasterDataTable(API_NAME);
final Function siteAggregationNow = CreateSiteAggregationNowFunction();

masterDataTable .grantReadData(siteAggregationNow);
Run Code Online (Sandbox Code Playgroud)

通过这几行代码,您已经创建了一个包含 DynamoDB 表(使用流)和从此表读取数据的 Lambda 的 CloudFormation 堆栈。