且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用Java连接池的AWS IAM数据库身份验证

更新时间:2023-12-02 20:50:58

我还不得不使用节点js lambda和MySql RDS来面对这个问题.我们使用的是 mysql 连接池,因此我们实施了一个解决方案,该解决方案创建了一个将来的日期时间,我们可以检查池中每次请求连接时连接是否即将到期.该日期时间是15分钟减去连接池初始化后的一些抖动.

I've also had to face this problem using node js lambda and MySql RDS. We were using a mysql connection pool and so we implemented a solution that created a future date-time that we could check to see if connections were about to expire whenever a connection was requested from the pool. This date-time was 15 minutes minus some jitter after the connection pool was initialized.

因此,获取连接池(以获取连接)将如下所示:

So getting the connection pool (to get a connection) would look like:

const getPool = async (): Promise<DbConnectionPool> => {
  if (isRdsIamTokenCloseToExpiring()) {
    await poolHolder.lock.acquire();
    try {
      // if, after having acquired lock, thread pool is still about to expire...    
      if (isRdsIamTokenCloseToExpiring()) {     
        await closeConnectionsInPool();
        await initializeConnectionPool();
      }
    } finally {
      poolHolder.lock.release();
    }
  }
  if (!poolHolder.pool) {
    throw new Error('pool holder is null - this should never happen');
  } else {
    return poolHolder.pool;
  }
};

因为我们有多个并发异步线程试图建立连接,所以我们不得不引入一个信号量来控制池的重新初始化.总而言之,与使用用户名&密码,但更安全.

Because we had multiple concurrent async threads trying to get a connection we had to introduce a semaphore to control the pool re-initialization. All in all having to do this was more cumbersome than using a username & password but it is more secure.

要回答以上Isen Ng的评论(我没有代表直接回答),RDS IAM令牌过期的连接将停止工作.

To answer Isen Ng's comment above (I don't have the rep to answer directly), connections whose RDS IAM token expires will stop working.