Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create multiple consumers in Kafka in command line

Tags:

apache-kafka

I'm new in Kafka. When I was running the quick start example in command line, I found I can't create multiple consumers in command line.

Condition:

I built a topic named test with 3 partitions, and I also built a producer on this topic.

Then I wanted to create two different consumers sharing a same consumer-group named test1 on this topic.

I ran the command like below twice:

   bin/kafka-console-consumer.sh --zookeeper localhost:2181 --topic test --group test1

The first one worked but when I ran the second time the first one would disconnect and the second one worked.

So how can I create two or more consumers in a same consumer group in command line?

    WARN Session 0x0 for server null, unexpected error, closing socket connection and attempting reconnect (org.apache.zookeeper.ClientCnxn)
java.net.ConnectException: Connection refused
    at sun.nio.ch.SocketChannelImpl.checkConnect(Native Method)
    at sun.nio.ch.SocketChannelImpl.finishConnect(SocketChannelImpl.java:739)
    at org.apache.zookeeper.ClientCnxn$SendThread.run(ClientCnxn.java:1146)
like image 598
user3526640 Avatar asked Oct 09 '14 23:10

user3526640


People also ask

How do you make multiple consumers in Kafka?

You can't have multiple consumers that belong to the same group in one thread and you can't have multiple threads safely use the same consumer. One consumer per thread is the rule. To run multiple consumers in the same group in one application, you will need to run each in its own thread.

Can Kafka have multiple consumers?

So the rule in Kafka is only one consumer in a consumer group can be assigned to consume messages from a partition in a topic and hence multiple Kafka consumers from a consumer group can not read the same message from a partition.

How do I add more consumers in a consumer group Kafka?

You cannot have more consumers in a group than partitions in your Kafka topic, and therefore we first need to create a Kafka topic with a few partitions (in the example 3). Each consumer in the consumer group my-first-application will get assigned a partition. Produce a few string messages in the topic.


2 Answers

Besides using --consumer.config option like the secfree's answer, you can also use

--consumer-property group.id=your_group

option to specify a group name without editing the config file.

like image 172
Joey Avatar answered Sep 24 '22 00:09

Joey


  1. Default, kafka-console-consumer.sh will create a random group.
  2. If you want to specify the group name, you can:
    1. Add group.id=group_name to a local file filename
    2. Use --consumer.config filename option of kafka-console-consumer.sh to set group
  3. You can check your groups at zookeeper's /consumers/ directory.

Refer: kafka/core/src/main/scala/kafka/tools/ConsoleConsumer.scala

like image 36
secfree Avatar answered Sep 24 '22 00:09

secfree