This is a simple example of how to use Kafka with Node.js created for the purpose of learning.
stateDiagram-v2
Producer --> Kafka: Messages
state Kafka {
[*] --> Topic_1: Message 1
[*] --> Topic_2: Message 2
Topic_1 --> Consumer_1: Message 1
Topic_2 --> Consumer_2: Message 2
state Group_1 {
Consumer_1
Consumer_2
}
Topic_1 --> Group_2: Message 1
Topic_2 --> Group_2: Message 2
state Group_2 {
[*] --> Consumer_X: Message 1
[*] --> Consumer_X: Message 2
}
}
- Docker
- Node.js
-
Clone this repository
-
Run
docker-compose up -d
to start Kafka and Zookeeper services -
Run
pnpm i
to install the dependenciesI have used
pnpm
to run the project, but you can usenpm
oryarn
as well. -
Once the docker containers are up and running, run
node admin.js
to create thetopics
-
Now, run
node consumer.js group-1
to start aconsumer
with the group namegroup-1
. Let's call thisconsumer-1
-
Next, create another terminal with the same command to start
consumer-2
with the same group namegroup-1
-
Next, create another terminal and run
node consumer.js group-2
to start theconsumer
with the group namegroup-2
. Let's call thisconsumer-x
-
Finally, run
node producer.js
to start theproducer
. -
To transmit a message we need to provide it in the following format:
[RIDER_NAME]<SPACE>[ZONE]<SPACE>[LATITUDE]<SPACE>[LONGITUDE]
eg: `rider-1 north 12.123456 12.123456`
P.s. Zone can be set to
north
orsouth
, since we have 2 partitions & subsequently support 2 consumers. -
Transmitting a message with zone
north
will be consumed by one of thegroup-1
consumers andconsumer-x
. -
Similarly, transmitting a message with zone
south
will be consumed by the othergroup-1
consumer andconsumer-x
.