---
title: 读副本连接
---

来源：https://mikro-orm.io/docs/read-connections

用户可以通过 `replicas` 选项指定多个读连接。你只需提供与主连接不同的字段，其余字段会从主连接继承。

解析读连接时，默认策略是为所有不在事务内运行的读操作（SELECT、COUNT）随机分配读副本。

你可以通过对应 Options 参数（即 `FindOptions`、`CountOptions`）上的 `connectionType` 属性，为 find 与 count 操作显式指定连接类型。

连接解析策略也可以反转：把 `preferReadReplicas` 配置属性设为 `false`，这样默认连接始终是写连接，除非显式请求读连接（在「读副本可用、但只应用于特定场景」的应用中这会很有用）。

```ts
const orm = await MikroORM.init({
  entities: [Author, ...],
  dbName: `my_database`,
  user: 'master_user',
  host: 'master_host',
  preferReadReplicas: true, // 可选属性，默认为 true
  replicas: [
    { name: 'read-1', host: 'read_host_1', user: 'read_user' },
    { name: 'read-2', host: 'read_host_2' }, // 省略了 user，会从主连接继承
  ],
});
```

默认情况下，如果不在事务内，select 查询会使用随机的读连接。你可以在 `em.getConnection(type: 'read' | 'write')` 中显式指定连接类型。

```ts
const connection = em.getConnection(); // 写连接
const readConnection = em.getConnection('read'); // 随机读连接

const qb1 = em.createQueryBuilder(Author);
const res1 = await qb1.select('*').execute(); // 随机读连接

const qb2 = em.createQueryBuilder(Author, 'a', 'write');
const res2 = await qb2.select('*').execute(); // 写连接

const qb3 = em.createQueryBuilder(Author);
const res3 = await qb3.update(...).where(...).execute(); // 写连接

const res4 = await em.findOne(Author, 1, { connectionType: 'write' }); // 显式写连接

// 事务内的所有查询都会使用写连接
await em.transactional(async em => {
    const a = await em.findOne(Author, 1); // 写连接
    const b = await em.findOne(Author, 1, { connectionType: 'read' }); // 仍然是写连接 ——我们在事务中
    a.name = 'test'; // flush 时会在写连接上触发更新
});

// 假设配置为 preferReadReplicas: false
const res5 = await em.findOne(Author, 1); // 写连接 ——即使是读操作
const res6 = await em.findOne(Author, 1, { connectionType: 'read' }); // 除非显式要求读副本
```
