rabbitmq NestJs/ClientProxy:手动侦听事件而不使用装饰器

mu0hgdu0  于 2023-06-23  发布在  RabbitMQ
关注(0)|答案(1)|浏览(150)

有没有一种手动的方法来订阅一个事件消息模式,而不需要在函数上使用装饰器?在服务中,我向不同的微服务发送消息。这个调用什么也不返回,只是void,但是异步触发了一个事件,我想在服务中立即监听这个事件
举个例子,也许会这样工作

// An event will be triggered later, after first value
await lastValueFrom(
  this.rabbitmqClient.send(RmqPatterns.DO_STUFF, payload),
);
    
// Now listening for that async event
this.rabbitmqClient.listen(RmqPatterns.DID_STUFF, async msg => {
  console.log(`Received message: ${msg.content.toString()}`);
});
nkoocmlb

nkoocmlb1#

你需要像这样创建客户端:(此代码未经测试,可能包含错别字等)

@Injectable()
export class MqttCoreService implements OnModuleInit {
  protected mqttClient: MqttClient;

  constructor(
    @Inject('MQTT_SERVICE_CORE') protected mqttCoreClient: ClientMqtt,
  ) {}

  async onModuleInit() {
    this.mqttClient = this.mqttCoreClient.createClient();

    // Get topics from some db and subscribe
    const topics = await this.someService.getTopics();
    topics.map(topic => {
      this.subscribe(topic);
    });

    this.mqttClient.on('message', handleMessage);
  }

  subscribe(topic: string) {
    return this.mqttClient.subscribe(topic);
  }

  async handleMessage(context: MqttContext, data: MqttCoreDtoModel | number) {...}
}

相关问题