TypeORM 0.3.6迁移后基于DataSource实现多租户DB连接的方案
TypeORM 0.3.6 多租户动态连接实现方案
0.3版本废弃全局ConnectionManager和createConnection是有意的设计调整,官方移除了内置的全局连接注册表,所有数据库连接都以独立DataSource实例形式存在,你之前的连接缓存逻辑思路完全成立,用轻量缓存存储租户对应的DataSource实例就是该场景下的标准实现,不属于不规范的自行维护。
对应旧逻辑的迁移实现
首先定义全局的租户DataSource缓存,直接用原生Map即可:
import { DataSource } from 'typeorm'; import { TenantModuleEntities } from './tenant.module'; // 租户数据源缓存,key为租户唯一标识 const tenantDataSourceCache = new Map<string, DataSource>();
实现和旧逻辑对齐的租户连接获取方法:
async function getTenantConnection(tenant: { name: string; host: string; port: number; username: string; password: string; database: string; }) { // 检查缓存中是否已存在对应租户的数据源 const cachedDataSource = tenantDataSourceCache.get(tenant.name); if (cachedDataSource) { // 0.3版本用isInitialized判断连接状态,对应旧版isConnected // initialize方法对应旧版connect,用于初始化未建立的连接 return cachedDataSource.isInitialized ? cachedDataSource : cachedDataSource.initialize(); } // 缓存不存在时创建新的DataSource实例 const dataSource = new DataSource({ type: 'postgres', host: tenant.host, port: tenant.port, username: tenant.username, password: tenant.password, database: tenant.database, entities: [...TenantModuleEntities], // 可按需配置连接池大小、超时、日志等参数 }); // 初始化连接后存入缓存 await dataSource.initialize(); tenantDataSourceCache.set(tenant.name, dataSource); return dataSource; }
关键注意事项
- 你可以按需扩展缓存逻辑,比如增加闲置连接回收:对超过一定时间无请求的租户,调用
dataSource.destroy()销毁连接,同时从Map中删除对应记录,避免闲置连接占用数据库资源,这是旧版全局ConnectionManager很难灵活实现的能力。 - 按请求分配连接时,只需要在请求入口(中间件、拦截器、守卫层)解析出当前请求对应的租户信息,调用上述方法拿到对应DataSource,后续数据库操作直接通过该DataSource实例获取Repository即可,API和旧版Connection基本一致:
- 旧版
connection.getRepository(Entity)→ 新版dataSource.getRepository(Entity) - 旧版
connection.manager→ 新版dataSource.manager
- 旧版
- 不要尝试找0.3版本里替代ConnectionManager的内置全局API,官方已经明确将多实例连接的管理职责交给业务侧实现,上述缓存方案是官方文档多租户、多数据库场景给出的参考实现方式。
内容的提问来源于stack exchange,提问作者Filip
相关产品推荐
相关产品推荐

