在 Sequelize 中将连接 URI 与读取复制结合使用

Par*_*rth 9 node.js sequelize.js

如果我有一个连接 URI,我通常可以将其与 Sequelize 一起使用,如下所示:

const sequelize = new Sequelize('postgres://user:pass@example.com:5432/dbname');
Run Code Online (Sandbox Code Playgroud)

但是,如果我想使用读写复制(https://sequelize.org/master/manual/read-replication.html),那么似乎没有使用连接 URI 的选项。我可以传递连接 URI 字符串以在复制选项中进行读写,如下所示:

const sequelize = new Sequelize('postgres://user:pass@example.com:5432/dbname');
Run Code Online (Sandbox Code Playgroud)

编辑:

我已经找到了解决该问题的方法。那就是使用像连接字符串这样的 npm 库来解析连接字符串,如下所示:

const write_uri = new ConnectionString(uri);
const sequelize = new Sequelize(null, null, null, {
  dialect: 'postgres',
  replication: {
    read: [
      'postgres://user:pass@reader.example.com:5432/dbname',
      'postgres://user:pass@anotherreader.example.com:5432/dbname'
    ],
    write: {
      host: write_uri.hosts[0].name,
      username: write_uri.user,
      password: write_uri.password,
      database: write_uri.path[0],
      port: write_uri.hosts[0].port
    }
  }
});
Run Code Online (Sandbox Code Playgroud)

但是,这不是我要找的。

Tri*_*hra 2

根据 master 的续集来源,你不能。

根据sequelize.js上的sequelize 源文档,Sequelize 构造函数接受options参数,如下所示

constructor(database, username, password, options){

}
Run Code Online (Sandbox Code Playgroud)

其中options.replication应该是一个具有两个属性的对象,读和写。写入应该是一个对象(单个服务器处理写入),而读取应该是一个对象数组(多个服务器处理读取)。每个读/写服务器可以具有以下属性:hostportusernamepassworddatabase

您需要传递一个带有连接值的数组objects作为read:[]props 而不是传递strings