Ask Your Question
1

How to turn off a consumer in the NestJS Kafka client?

asked 2023-05-04 23:39:07 +0000

djk gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2023-05-05 00:04:02 +0000

scrum gravatar image

To turn off a consumer in the NestJS Kafka client, you can use the close() method provided by the Consumer object.

import { Controller } from '@nestjs/common';
import { MessagePattern } from '@nestjs/microservices';
import { Kafka } from 'kafkajs';

@Controller()
export class MyController {
  private kafka: Kafka;
  private consumer: Consumer;

  constructor() {
    this.kafka = new Kafka({
      clientId: 'my-app',
      brokers: ['localhost:9092'],
    });

    this.consumer = this.kafka.consumer({
      groupId: 'my-group',
    });

    this.consumer.connect();
  }

  @MessagePattern('my-topic')
  public async processMessage(payload: any) {
    console.log(`Received message: ${JSON.stringify(payload)}`);
    // process the message here
  }

  public async closeConsumer() {
    await this.consumer.disconnect();
  }
}

Once you're ready to turn off the consumer, simply call the closeConsumer() method. This will disconnect the consumer from the Kafka cluster and stop consuming messages.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-05-04 23:39:07 +0000

Seen: 15 times

Last updated: May 05 '23