将 node-postgres 连接到 PostgreSQL 方言数据库

本页介绍如何将 PostgreSQL node-postgres 驱动程序连接到 Spanner 中的 PostgreSQL 方言数据库。node-postgres 是适用于 PostgreSQL 的 Node.js 驱动程序。

  1. 验证 PGAdapter 与使用 PostgreSQL node-postgres 驱动程序连接的应用位于同一台机器上。

    如需了解详情,请参阅启动 PGAdapter

  2. node-postgres 连接属性中指定数据库服务器主机和端口:

    const { Client } = require('pg');
    const client = new Client({
      host: 'APPLICATION_HOST',
      port: PORT,
      database: 'DATABASE_NAME',
    });
    await client.connect();
    const res = await client.query("select 'Hello world!' as hello");
    console.log(res.rows[0].hello);
    await client.end();
    

    替换以下内容:

    • APPLICATION_HOST:运行 PGAdapter 的机器的主机名或 IP 地址。如果在本地运行,您可以使用 localhost
    • PORT:PGAdapter 正在运行的端口号。如果 PGAdapter 在自定义端口上运行,请在连接字符串中更改此设置。否则,请使用默认端口 5432

Unix 网域套接字

本部分介绍如何使用 Unix 网域套接字将 PostgreSQL node-postgres 驱动程序连接到 PostgreSQL 方言数据库。如果您需要尽可能缩短延迟时间,请使用 Unix 网域套接字连接。

如需使用 Unix 网域套接字,PGAdapter 必须与客户端应用在同一主机上运行。

const client = new Client({
  host: '/tmp',
  port: PORT,
  database: 'DATABASE_NAME',
});
await client.connect();
const res = await client.query("select 'Hello world!' as hello");
console.log(res.rows[0].hello);
await client.end();

替换以下内容:

  • /tmp:PGAdapter 的默认网域套接字目录。您可以使用 -dir 命令行参数更改此设置。
  • PORT:PGAdapter 正在运行的端口号。如果 PGAdapter 在自定义端口上运行,请在连接字符串中更改此设置。否则,请使用默认端口 5432

后续步骤