Skip to main content
Version: v6 - stable

读复制

Sequelize 支持 读复制,即当你想要执行 SELECT 查询时可以连接到多个服务器。进行读复制时,你指定一台或多台服务器充当只读副本,并指定一台服务器充当主写入器,该服务器处理所有写入和更新并将它们传播到副本(请注意,实际的复制过程不被处理) 通过 Sequelize,但应由数据库后端设置)。

¥Sequelize supports read replication, i.e. having multiple servers that you can connect to when you want to do a SELECT query. When you do read replication, you specify one or more servers to act as read replicas, and one server to act as the main writer, which handles all writes and updates and propagates them to the replicas (note that the actual replication process is not handled by Sequelize, but should be set up by database backend).

const sequelize = new Sequelize('database', null, null, {
dialect: 'mysql',
port: 3306,
replication: {
read: [
{ host: '8.8.8.8', username: 'read-1-username', password: process.env.READ_DB_1_PW },
{ host: '9.9.9.9', username: 'read-2-username', password: process.env.READ_DB_2_PW }
],
write: { host: '1.1.1.1', username: 'write-username', password: process.env.WRITE_DB_PW }
},
pool: { // If you want to override the options used for the read/write pool you can do so here
max: 20,
idle: 30000
},
})

如果你有任何适用于所有副本的常规设置,则无需为每个实例提供它们。在上面的代码中,数据库名称和端口被传播到所有副本。如果你为任何副本保留用户和密码,也会发生同样的情况。每个副本都有以下选项:hostportusernamepassworddatabase

¥If you have any general settings that apply to all replicas you do not need to provide them for each instance. In the code above, database name and port is propagated to all replicas. The same will happen for user and password, if you leave them out for any of the replicas. Each replica has the following options:host,port,username,password,database.

Sequelize 使用池来管理与副本的连接。Sequelize 在内部将维护两个使用 pool 配置创建的池。

¥Sequelize uses a pool to manage connections to your replicas. Internally Sequelize will maintain two pools created using pool configuration.

如果要修改这些,可以在实例化 Sequelize 时将 pool 作为选项传递,如上所示。

¥If you want to modify these, you can pass pool as an options when instantiating Sequelize, as shown above.

每个 writeuseMaster: true 查询都将使用写入池。对于 SELECT,将使用读取池。使用基本的循环调度来切换只读副本。

¥Each write or useMaster: true query will use write pool. For SELECT read pool will be used. Read replica are switched using a basic round robin scheduling.