如何设计一个通用的翻译服务,支持动态加载语言包?
解读
国内中大型企业后端普遍要求“国际化”能力,但语言包往往由运营/翻译团队持续更新,不能随发版硬编码。NestJS 项目里常见痛点有三:
- 语言包体积大,不能全部打进 Docker 镜像;
- 需要运行时热更新,重启 Pod 会丢缓存;
- 微服务场景下,网关、BFF、Admin 多个服务要共用同一套翻译。
因此面试官想考察:
- 是否理解 IoC 与模块化设计,能把“翻译”做成可插拔的 Platform 能力;
- 是否掌握动态模块、惰性加载、缓存、文件监听、分布式同步等落地细节;
- 是否考虑性能(内存、I/O)、高可用(灰度、回滚)、可观测(指标、日志)。
知识点
- Dynamic Module + Global Module:运行时按配置注册,保证单例。
- lazy-import 与 promise-cache:语言包按命名空间切割,首次访问时下载并缓存,后续命中内存。
- node-watch/chokidar:监听 OSS/MinIO 本地挂载目录,文件变动后刷新 LRU 缓存并广播事件。
- Redis / ETCD:多实例间同步“语言包版本号”,配合版本对比实现热更新。
- Decorator 与 Pipe:@Lang() 提取 header/cookie/query 中的语言偏好,@I18n() 在 Controller 层直接注入翻译函数 t。
- GraphQL Plugin:在 field 中间件层自动解析 description 与错误消息。
- 微服务传输:基于 gRPC 的 Metadata 透传 lang 标签,避免每个服务再次解析。
- 指标:Prometheus counter(i18n_cache_hit_total、i18n_load_failure_total)与 histogram(i18n_load_duration_seconds)。
- 灰度方案:语言包带版本号与灰度标签,通过配置中心按用户维度百分比下发。
- 单元测试:使用 memfs 伪造磁盘,snapshot 对比不同语言输出,确保 key 缺失时降级到默认语言并报警。
答案
- 模块定义
@Global()
@Module({})
export class I18nModule {
static forRoot(options: I18nOptions): DynamicModule {
return {
module: I18nModule,
providers: [
{ provide: I18N_OPTIONS, useValue: options },
I18nService,
{
provide: APP_INTERCEPTOR,
useClass: I18nInterceptor, // 自动把 t 函数注入 request 上下文
},
],
exports: [I18nService],
};
}
}
- 语言包加载器
@Injectable()
export class I18nLoader {
constructor(@Inject(I18N_OPTIONS) private opt: I18nOptions) {}
async load(lang: string, ns: string): Promise<Record<string, string>> {
const localPath = join(this.opt.localDir, lang, `${ns}.json`);
if (await pathExists(localPath)) return readJSON(localPath);
// 未命中则去 OSS 拉取
const remoteUrl = `${this.opt.ossDomain}/${lang}/${ns}.json`;
const remote = await firstValueFrom(this.http.get(remoteUrl));
await outputJSON(localPath, remote.data, { spaces: 2 });
return remote.data;
}
}
- 缓存与热更新
@Injectable()
export class I18nService implements OnModuleInit {
private readonly cache = new LRU<string, Record<string, string>>(500);
private readonly versionKey = 'i18n:version';
async onModuleInit() {
watch(this.opt.localDir, { recursive: true }, (_, file) => {
if (!file.endsWith('.json')) return;
const [, lang, ns] = file.split(sep);
this.cache.del(`${lang}:${ns}`);
this.redis.publish('i18n:reload', `${lang}:${ns}`);
});
this.redis.subscribe('i18n:reload', (msg) => this.cache.del(msg));
}
async t(lang: string, key: string, vars?: Record<string, any>) {
const [ns, ...rest] = key.split('.'); // 支持命名空间
const dict = await this.getDict(lang, ns);
const tmpl = dict[rest.join('.')] ?? key;
return template(tmpl)(vars);
}
private async getDict(lang: string, ns: string) {
const ck = `${lang}:${ns}`;
if (this.cache.has(ck)) return this.cache.get(ck)!;
const dict = await this.loader.load(lang, ns);
this.cache.set(ck, dict);
return dict;
}
}
- 使用侧
@Get('hello')
async hello(@Lang() lang: string) {
return { msg: await this.i18n.t(lang, 'common.welcome', { name: 'Nest' }) };
}
- 灰度与回滚
语言包 JSON 增加_meta:{version,grayPercent}字段,I18nService 根据用户 ID hash 判断是否命中灰度版本,否则回退到上一稳定版本;版本号写入 Redis,Admin 后台一键回滚只需把版本号指针前移。
拓展思考
- Serverless 场景下冷启动敏感,可把高频语言包预置到层(Layer)或快照,边缘函数通过请求参数直读层内文件,跳过网络 IO。
- 借助 NestJS 的 GraphQL 插件机制,可在编译期把
@Field({ description: i18n('user.name') })中的 description 自动展开成多语言,实现 API 文档国际化。 - 对于 SSR 前端,考虑在网关层把
Accept-Language解析后注入x-lang响应头,并设置Cache-Control: public, max-age=300, s-maxage=600, stale-while-revalidate=1200,实现边缘 CDN 按语言缓存,减少回源。 - 若团队使用 Monorepo,可把语言包作为独立 npm workspace,每次 MR 触发 CI 构建时自动执行
i18n extract扫描代码中的 key,与上一版本 diff,产出“未翻译 key 列表”推送给翻译平台,实现 DevOps 闭环。