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

如何在CDK中为ServerlessCluster创建DatabaseProxy?

解决AWS CDK中Aurora Serverless集群与RDS Proxy的类型兼容问题

你遇到的问题是ServerlessCluster实现的IServerlessCluster接口,与DatabaseProxy构造函数要求的IDatabaseCluster接口不兼容,直接使用ProxyTarget.fromCluster()会触发类型错误。

解决方法很直接:使用ProxyTarget.fromServerlessCluster()替代fromCluster(),该方法专门针对IServerlessCluster类型的集群创建代理目标。

修正后的代码片段

// 替换原有的Proxy创建代码
const proxy = new DatabaseProxy(scope, 'Proxy', {
    proxyTarget: ProxyTarget.fromServerlessCluster(dbCluster), // 改用专门适配Serverless集群的方法
    secrets: [dbCluster.secret!],
    vpc,
});

完整修正代码

import { 
    AuroraPostgresEngineVersion,
    AuroraCapacityUnit,
    DatabaseClusterEngine,
    DatabaseProxy,
    ProxyTarget,
    ServerlessCluster
} from 'aws-cdk-lib/aws-rds';
import { Duration, RemovalPolicy } from 'aws-cdk-lib';
import { IVpc, ISecurityGroup, SubnetType } from 'aws-cdk-lib/aws-ec2';
import { Construct } from 'constructs';
import { Stage } from '../../bin/bin';

interface Props {
    scope: Construct;
    stage: Stage;
    name: string;
    vpc: IVpc;
    sgs: ISecurityGroup[];
    engineVersion?: AuroraPostgresEngineVersion;
}

export const createAuroraPostgresRdsServerlessClusterWithProxy = ({
    scope,
    stage,
    name,
    vpc,
    sgs,
    engineVersion
  }: Props) => {

    const dbCluster = new ServerlessCluster(scope, name, {
        engine: DatabaseClusterEngine.auroraPostgres({
          version: engineVersion ?? Object.values(AuroraPostgresEngineVersion).slice(-1)[0]
        }),
        vpc,
        securityGroups: sgs,
        removalPolicy: RemovalPolicy.DESTROY,
        defaultDatabaseName: 'myDatabaseName',
        clusterIdentifier: `myClusterId`,
        scaling: { 
            autoPause: Duration.minutes(5),
            minCapacity: stage === 'dev' ? AuroraCapacityUnit.ACU_2 : AuroraCapacityUnit.ACU_8,
            maxCapacity: stage === 'dev' ? AuroraCapacityUnit.ACU_16 : AuroraCapacityUnit.ACU_64,
        },
        vpcSubnets: {
            subnetType: stage === 'dev' ? SubnetType.PUBLIC : SubnetType.PRIVATE_ISOLATED
        },
    });

    // 修正后的Proxy创建逻辑
    const proxy = new DatabaseProxy(scope, 'Proxy', {
        proxyTarget: ProxyTarget.fromServerlessCluster(dbCluster),
        secrets: [dbCluster.secret!],
        vpc,
    });
    
}

关键说明

  • ProxyTarget提供了两类静态方法适配不同集群类型:fromCluster()对应传统DatabaseCluster(实现IDatabaseCluster接口),fromServerlessCluster()对应ServerlessCluster(实现IServerlessCluster接口)。
  • 若你的CDK版本过旧可能没有fromServerlessCluster()方法,建议升级至稳定版。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 11:42:58