node.js - 引导微服务时获取 ConfigService 的正确方法
问题描述
我想知道在引导我的微服务期间我是否以正确的方式获得了 ConfigService。
有没有办法使用 NestFactory.createMicroservice() 来做到这一点?
async function bootstrap() {
const app = await NestFactory.create(CoreModule, {
logger: new MyLogger(),
});
const configService: ConfigService = app.get(ConfigService);
app.connectMicroservice({
transport: Transport.TCP,
options: {
port: configService.PORT,
},
});
await app.startAllMicroservicesAsync();
}
解决方案
是的,在 NestFactory 中有一种方法可以做到这一点,您已经以正确的方式做到了!如果你想要另一个例子,这是我的引导函数:
async function bootstrap() {
const app = await NestFactory.create(AppModule, {
logger: new MyLogger()
});
const config = app.get<ConfigService>(ConfigService);
const port = config.get('PORT');
configure(app, config);
await app.listen(port);
scribe.info(
`Listening at http://localhost:${port}/${config.get('GLOBAL_PREFIX')}`
);
}
MyLogger
Nest 默认记录器的自定义实现在哪里,并且configure(app, config)
大量应用程序配置在单独的文件中完成,以保持bootstrap
功能精简和易于维护。当然,“收听...”也需要在投入生产之前进行更改,但这个应用程序对我来说仍在开发中。
我唯一建议你的是改变
const configService: ConfigService = app.get(ConfigService);
至
const configService = app.get<ConfigService>(ConfigService);
使用泛型为app.get()
您提供类型信息。
推荐阅读
- c++ - C ++:从离散分布中抽样而不进行替换
- java - 是否有任何用 Java 构建的方式来用 2 个整数的组合制作一个集合?
- database-design - 如何在 Spanner 中高效地创建强有序序列?
- c++ - 使用 SIGINT 停止计划任务
- javascript - 使用 SQL 进行 AES 加密,然后使用 Javascript 进行解密
- artifactory - 如何将 google maven 存储库添加到工件中的远程存储库
- c# - 是否有 object[] 框
- php - API 图像对 AWS S3 的响应 [PHP]
- javascript - 如何测试具有多个输入的 api POST 调用
- javascript - Vue + SSR webpackJsonp 未定义