简体   繁体   English

如何使用 Serverless Framework 管理 Lambda 内部的 Aurora Serverless 数据 api 的 typeORM 连接

[英]How to manage typeORM connection of Aurora Serverless data api inside Lambda using Serverless Framework

I'm using:我在用着:

I'm connecting to the db like it's described in github,我正在连接到数据库,就像 github 中描述的那样,

const connection = await createConnection({
      type: 'aurora-data-api-pg',
      database: 'test-db',
      secretArn: 'arn:aws:secretsmanager:eu-west-1:537011205135:secret:xxxxxx/xxxxxx/xxxxxx',
      resourceArn: 'arn:aws:rds:eu-west-1:xxxxx:xxxxxx:xxxxxx',
      region: 'eu-west-1'
    })

And this is how I use it inside of my Lambda function这就是我在 Lambda function 中使用它的方式

export const testConfiguration: APIGatewayProxyHandler = async (event, _context) => {
  let response;
  try {
    const connectionOptions: ConnectionOptions = await getConnectionOptions();
    const connection = await createConnection({
      ...connectionOptions,
      entities,
    });
    const userRepository = connection.getRepository(User);
    const users = await userRepository.find();

    response = {
      statusCode: 200,
      body: JSON.stringify({ users }),
    };
  } catch (e) {
    response = {
      statusCode: 500,
      body: JSON.stringify({ error: 'server side error' }),
    };
  }
  return response;
};

When I execute is first time it works just well.当我第一次执行时,它运行良好。

But second and next times I'm getting an error但是第二次和下一次我得到一个错误

AlreadyHasActiveConnectionError: Cannot create a new connection named "default", because connection with such name already exist and it now has an active connection session.

So, what is the proper way to manage this connection?那么,管理此连接的正确方法是什么? Should it be somehow reused?它应该以某种方式重用吗?

I've found some resolutions for simple RDS but the whole point of Aurora Serverless Data API is that you don't have to manage the connection我找到了一些简单 RDS 的解决方案,但 Aurora Serverless Data API的全部意义在于您不必管理连接

when you try to establish a connection, you need to check if there is already a connection it can use.当您尝试建立连接时,您需要检查是否已经存在可以使用的连接。 this is my Database class used to handle connections这是我的Database class 用于处理连接

export default class Database {
  private connectionManager: ConnectionManager;

  constructor() {
    this.connectionManager = getConnectionManager();
  }

  async getConnection(): Promise<Connection> {
    const CONNECTION_NAME = 'default';

    let connection: Connection;

    if (this.connectionManager.has(CONNECTION_NAME)) {
      logMessage(`Database.getConnection()-using existing connection::: ${CONNECTION_NAME}`);
      connection = await this.connectionManager.get(CONNECTION_NAME);

      if (!connection.isConnected) {
        connection = await connection.connect();
      }
    } else {
      logMessage('Database.getConnection()-creating connection ...');
      logMessage(`DB host::: ${process.env.DB_HOST}`);

      const connectionOptions: ConnectionOptions = {
        name: CONNECTION_NAME,
        type: 'postgres',
        port: 5432,
        logger: 'advanced-console',
        logging: ['error'],
        host: process.env.DB_HOST,
        username: process.env.DB_USERNAME,
        database: process.env.DB_DATABASE,
        password: process.env.DB_PASSWORD,
        namingStrategy: new SnakeNamingStrategy(),
        entities: Object.keys(entities).map((module) => entities[module]),
      };

      connection = await createConnection(connectionOptions);
    }

    return connection;
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM