【问题标题】:Using BullMQ with NestJs, is it possible to use a config variable as part of a Job name?将 BullMQ 与 NestJs 一起使用,是否可以将配置变量用作作业名称的一部分?
【发布时间】:2022-01-26 19:30:03
【问题描述】:

我正在尝试在 nestjs/bull 模块的 @Process() 装饰器中使用环境变量值,如下所示。我应该如何提供“STAGE”变量作为作业名称的一部分?

import { Process, Processor } from '@nestjs/bull';
import { Inject } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { Job } from 'bull';

@Processor('main')
export class MqListener {

  constructor(
    @Inject(ConfigService) private configService: ConfigService<SuperRootConfig>,
  ) { }

  // The reference to configService is not actually allowed here:
  @Process(`testjobs:${this.configService.get('STAGE')}`)
  
  handleTestMessage(job: Job) {
    console.log("Message received: ", job.data)
  }
}

编辑了 Micael 和 Jay 的答案(如下):

Micael Levi 回答了最初的问题:您不能使用 NestJS ConfigModule 将您的配置放入内存变量中。但是,在引导函数中运行 dotenv.config() 也不起作用;如果您尝试从方法装饰器中访问它们,您将获得未定义的内存变量值。为了解决这个问题,Jay McDoniel 指出您必须在导入 AppModule 之前导入文件。所以这行得通:

// main.ts
import { NestFactory } from '@nestjs/core';
require('dotenv').config()
import { AppModule } from './app.module';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  await app.listen(process.env.PORT || 4500);
}
bootstrap();

【问题讨论】:

    标签: dependency-injection nestjs bullmq


    【解决方案1】:

    由于decorator evaluation 的工作方式,您不能在该上下文中使用this。当时还没有为MqListener 类创建实例,因此使用this.configService 没有意义。

    您需要直接访问process.env.。因此将在该文件中调用dotenv(或读取和解析您的 dot env 文件的库)。

    【讨论】:

    • 谢谢。我曾尝试直接访问 process.env 但调用时该值未定义。除了通过 ConfigService 加载(看起来没用),我还尝试在启动时在 app.listen() 之前在 main.ts 中使用 dotenv.config() 加载它。该值仍然未定义:@Process(${process.env.STAGE}) 未定义传递。我错过了什么吗?
    • 在导入app.module 文件之前 是否致电dotenv.config()?订单在这里很重要
    • 这样就行了。对于以后阅读的任何 Nest 新手,我将在下面添加添加代码以清楚起见。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-04
    • 1970-01-01
    • 2022-01-13
    • 2014-03-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多