我正在使用@golevelup/nestjs-rabbitmq
库构建一个NestJS应用程序,以将消息发布到rabbitmq交换。
我正在AppModule中导入和配置RabbitMQ模块(这部分看起来工作正常)。
我创建了一个名为MessagingModule的模块和一个服务MessagingService。但是,当我尝试创建MessagingService并将AmqpConnection对象注入到构造函数中时,出现了一个错误。
错误:
error: Nest can't resolve dependencies of the RabbitMQModule (DiscoveryService, ExternalContextCreator, ?, AmqpConnectionManager). Please make sure that the argument RabbitRpcParamsFactory at index [2] is available in the RabbitMQModule context.
Potential solutions:
- Is RabbitMQModule a valid NestJS module?
- If RabbitRpcParamsFactory is a provider, is it part of the current RabbitMQModule?
- If RabbitRpcParamsFactory is exported from a separate @Module, is that module imported within RabbitMQModule?
应用模块
import { ConfigModule } from '@nestjs/config';
import { configuration } from './config/configuration';
import { MessagingModule } from './messaging/messaging.module';
import { RabbitMQModule } from '@golevelup/nestjs-rabbitmq';
import { ConfigService } from '@nestjs/config';
@Module({
imports: [
ConfigModule.forRoot({
isGlobal: true,
cache: true,
load: [configuration],
validationSchema,
validationOptions: {
allowUnkown: false,
abortEarly: true,
},
}),
RabbitMQModule.forRootAsync(RabbitMQModule, {
imports: [ConfigModule],
inject: [ConfigService],
useFactory: async (configService: ConfigService) => ({
exchanges: [
{
name: configService.get<string>('RABBITMQ_EXCHANGE'),
type: configService.get<string>('RABBITMQ_EXCHANGE_TYPE'),
},
],
uri: configService.get<string>('RABBITMQ_URL'),
channels: {
'channel-1': {
prefetchCount: 15,
default: true,
},
'channel-2': {
prefetchCount: 2,
},
},
connectionInitOptions: { wait: false },
enableControllerDiscovery: true,
}),
}),
MessagingModule,
],
controllers: [],
providers: [],
})
export class AppModule {}
消息模块
import { RabbitMQModule } from '@golevelup/nestjs-rabbitmq';
import { Module } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { MessagingService } from './messaging.service';
import { MessagingController } from './messaging.controller';
@Module({
imports: [
RabbitMQModule,
MessagingModule,
],
providers: [ConfigService, MessagingService],
controllers: [MessagingController],
exports: [MessagingService],
})
export class MessagingModule {}
消息服务
import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { AmqpConnection } from '@golevelup/nestjs-rabbitmq';
@Injectable()
export class MessagingService {
constructor(private readonly amqpConnection: AmqpConnection) {}
// Publish the event to the exchange
public async publish<T>(exchange: string, event: T): Promise<void> {
await this.amqpConnection.publish(exchange, '', event);
}
}
1条答案
按热度按时间pnwntuvh1#
每次要使用
RabbitMQModule
时,都需要使用forRoot
/forRootAsync
方法来确保设置了模块所需的所有提供程序。如果你想只调用一次,你可以为它设置一个 Package 器模块,如下所示:现在,您可以添加
RabbitModule
而不是RabbitMQModule
,并且每次都将获得预配置的相同RabbitMQModule
。