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

Spring响应式服务AWS RDS无密码IAM认证令牌过期问题求助

问题:R2DBC连接AWS RDS时IAM认证令牌过期导致连接断开

我的Spring服务采用响应式架构,使用R2DBC建立数据库连接。已成功为AWS RDS启用IAM无密码认证,但认证令牌仅拥有15分钟有效期,过期后数据库连接会断开。尝试过用@Scheduled注解和RefreshingConnectionFactory解决该问题,但未成功。相关实现代码及配置如下:

实现代码

@Bean
public ConnectionFactory connectionFactory() {
    // 扮演IAM角色
    StsClient stsClient = StsClient.builder().region(Region.EU_WEST_1).build();
    AssumeRoleRequest assumeRoleRequest = AssumeRoleRequest.builder()
            .roleArn("arn")
            .roleSessionName("CrossAccountDbSession")
            .build();
    AssumeRoleResponse assumeRoleResponse = stsClient.assumeRole(assumeRoleRequest);
    Credentials assumedCredentials = assumeRoleResponse.credentials();

    // 创建带扮演角色的AWS凭证提供者
    AwsCredentialsProvider credentialsProvider = () -> software.amazon.awssdk.auth.credentials.AwsSessionCredentials.create(
            assumedCredentials.accessKeyId(),
            assumedCredentials.secretAccessKey(),
            assumedCredentials.sessionToken()
    );

    // 生成IAM认证令牌
    RdsUtilities rdsUtilities = RdsUtilities.builder().region(Region.EU_WEST_1).build();
    String authToken = rdsUtilities.generateAuthenticationToken(builder -> builder
            .hostname("host-name")
            .port(5432)
            .username("username")
            .credentialsProvider(credentialsProvider)
    );

    PostgresqlConnectionConfiguration postgresConfig = PostgresqlConnectionConfiguration.builder()
        .host("hostname")
        .port(5432)
        .username("username")
        .password(authToken)
        .database("databasename")
        .build();

    ConnectionPoolConfiguration poolConfig = ConnectionPoolConfiguration.builder(new PostgresqlConnectionFactory(postgresConfig))
        .maxIdleTime(Duration.ofMinutes(15)) // 连接闲置15分钟后关闭
        .maxSize(20) // 连接池最大连接数
        .initialSize(5) // 连接池初始连接数
        .build();

    return new ConnectionPool(poolConfig);
}

配置文件(application-dev.properties)

server.port=8114

######### PostgreSQL数据库配置 #########

aws.rds.region=eu-west-1
aws.rds.host=host
aws.rds.port=5432
aws.rds.dbname=dbname

spring.r2dbc.username=username
spring.r2dbc.password=
spring.r2dbc.url= r2dbc:postgresql://rds/dbname
spring.datasource.driver-class-name=org.postgresql.Driver
spring.jpa.database-platform=org.hibernate.dialect.PostgreSQL9Dialect

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 11:43:22