可以在nestjs客户端rmq中添加对主题交换的支持

时间:2019-07-07 10:20:52

标签: nestjs

我需要通过RabbitMQ的主题交换来发送数据,并且要做到这一点,我创建了一个从ClientProxy继承的RmqClient,并且可以重用在其中创建连接的send方法。

可能的支持主题,扇出...在本机客户端rmq中?

我们创建了一个接口以支持主题交换选项,并创建了一种方法来接收routingKey和数据作为参数。

这是我们的代码:

export interface RmqClientOptions {
  urls: string[];
  exchangeName: string;
  exchangeType: 'fanout' | 'topic';
  exchangeOptions?: any;
  socketOptions?: any;
}

@Module({})
export class RmqClientModule {
  static register(name: string, clientOptions: RmqClientOptions): DynamicModule {
    const client = {
      provide: name,
      useValue: new RmqClient(clientOptions),
    };
    return {
      module: RmqClientModule,
      providers: [client],
      exports: [client],
    };
  }
}
  //RmqClient

  public createChannel(): Promise<void> {
    return new Promise(resolve => {
      this.channel = this.client.createChannel({
        json: false,
        setup: (channel: any) => this.setupChannel(channel, resolve),
      });
    });
  }

  public async setupChannel(channel: any, resolve: Function) {
    await channel.assertExchange(this.exchangeName, this.exchangeType, this.exchangeOptions);
    resolve();
  }

  protected publish(packet: ReadPacket<any>, callback: (packet: WritePacket<any>) => any): Function {
    try {
//packet.pattern is our routingKey
      this.channel.publish(this.exchangeName, packet.pattern, Buffer.from(JSON.stringify(packet.data)));
      return () => true;
    } catch (err) {
      callback({ err });
    }
  }

  public sendSingleMessage(routingKey: any, data: any): Promise<any> {
    return this.send(routingKey, data).toPromise();
  }

}
//using the client
@Injectable()
export class AppService {

  constructor(@Inject('RMQ_CLIENT') private readonly client: RmqClient) { }

  sendMessage(): void {
    this.client.sendSingleMessage('error', { user: 'kako', message: 'user created' });
  }

0 个答案:

没有答案