【问题标题】:How to publish to Kafka client in NestJS?如何在 NestJS 中发布到 Kafka 客户端?
【发布时间】:2021-01-31 17:51:36
【问题描述】:

我尝试在 NestJs 中发布到 kafka

 async publish<T extends IEvent>(event: T) {
    await this.client.connect();
    await this.client.send('topic', event);
  }

但还没有找到正确的方法,dispatchEvent 是受保护的。

编辑: 使用 cqrs 所以这是在订阅事件总线的事件发布者中。

【问题讨论】:

    标签: nestjs


    【解决方案1】:

    我认为您不需要connect 方法。你确定你是subscribing to the message response 吗?下面是一个带有客户端控制器和服务器控制器的工作示例:

    客户端控制器

    import {
      Controller,
      Get,
      Inject,
      OnModuleDestroy,
      OnModuleInit,
      UseFilters,
    } from '@nestjs/common';
    import { ClientKafka } from '@nestjs/microservices';
    import { ExceptionFilter } from './exception.filter';
    
    @Controller()
    export class KafkaClientController implements OnModuleInit, OnModuleDestroy {
      constructor(@Inject('KAFKA_SERVICE') private readonly kafka: ClientKafka) {}
    
      async onModuleInit() {
        ['hello', 'error', 'skip'].forEach((key) =>
          this.kafka.subscribeToResponseOf(`say.${key}`),
        );
      }
    
      onModuleDestroy() {
        this.kafka.close();
      }
    
      @Get()
      sayHello() {
        return this.kafka.send('say.hello', { ip: '127.0.0.1' });
      }
    
      @Get('error')
      @UseFilters(ExceptionFilter)
      sayError() {
        return this.kafka.send('say.error', { ip: '127.0.0.1' });
      }
    
      @Get('skip')
      saySkip() {
        return this.kafka.send('say.skip', { ip: '127.0.0.1' });
      }
    }
    

    服务器控制器

    import { BadRequestException, Controller, UseFilters } from '@nestjs/common';
    import { MessagePattern } from '@nestjs/microservices';
    import { OgmaSkip } from '@ogma/nestjs-module';
    import { AppService } from '../../app.service';
    import { ExceptionFilter } from './exception.filter';
    
    @Controller()
    export class KafkaServerController {
      constructor(private readonly service: AppService) {}
    
      @MessagePattern('say.hello')
      sayHello() {
        return this.service.getHello();
      }
    
      @UseFilters(ExceptionFilter)
      @MessagePattern('say.error')
      sayError() {
        throw new BadRequestException('Borked');
      }
    
      @OgmaSkip()
      @MessagePattern('say.skip')
      saySkip() {
        return this.service.getHello();
      }
    }
    

    以上内容用于我正在制作的库的集成测试。你可以check out the full module setups here

    【讨论】:

    • 我在 cqrs 发布者中使用 kafka 来监听事件总线,稍后我将发布代码。这就是我使用连接的原因。我切换到只使用 kafka js 更方便。
    • 是的,这确实有效。我将 sayHello() 修改为:@Get() sayHello() { this.kafka.send('say.hello', { ip: '127.0.0.1' }); return 'hello' } 但这不起作用。有没有办法不用返回就可以使用send()
    • 您可以添加.subscribe()。之所以有必要,是因为它是一个 RxJS Observable,在有订阅者收听它之前,它们不会被触发。
    • 知道了。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2015-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-22
    • 1970-01-01
    • 1970-01-01
    • 2017-11-01
    相关资源
    最近更新 更多