Kafka with Ruby

Armando Couto 🇧🇷
2 min readMay 30, 2023
Photo by Joshua Fuller on Unsplash

Here’s an example of how you can use Ruby with Kafka using the ruby-kafka gem. Make sure you have the ruby-kafka gem installed before running this code.

In this example, we first create a Kafka client using the 'Kafka.new' method, specifying the seed brokers and a client ID. Then, we create a producer and a consumer using the Kafka client. We define the topic we want to produce and consume messages from.

To publish messages, we use the 'produce' method of the producer object, specifying the message and the topic. After producing the messages, we call 'deliver_messages' to send the messages to Kafka.

To consume messages, we use the 'subscribe' method of the consumer object to subscribe to the topic. Then, we use the 'each_message' method to iterate over the messages received from Kafka.

Finally, we close the producer and consumer connections using 'shutdown' and 'stop', respectively.

Note that you need to replace "localhost:9092" with the actual address of your Kafka brokers, and 'my_topic' with the desired topic name.

Remember to install the ruby-kafka gem by running 'gem install ruby-kafka' before running this code.

Tenho alguns outros tutoriais que podem ajudar, clique aqui para acessá-los.

Este texto foi útil? Então clique nas palminhas para avaliá-lo e incentivar a produção de novos artigos.

Até mais!

--

--