Kafka Using Java. Part 2.

Distributed Systems Development A-Z Guide.

Dmytro Nasyrov
Pharos Production
3 min readFeb 6, 2019

--

Kafka Using Java

Give us a message if you’re interested in Blockchain and FinTech software development or just say Hi at Pharos Production Inc.

Or follow us on Youtube to know more about Software Architecture, Distributed Systems, Blockchain, High-load Systems, Microservices, and Enterprise Design Patterns.

Pharos Production Youtube channel

In the previous two articles, we have described Apache Kafka installation into MacOS environment for development purposes.

How to install Apache Kafka on MacOS

Also, we have explained how to use Kafka with Java.

Kafka Using Java. Part 1.

But there is another approach more related to single-time fetch. For example, you want to read the first 5 messages and that’s all. This approach is called Assign and Seek.

We can use the same project from Part 1. Let’s add a new class AssignSeekConsumer.

Assign and Seek Consumer class.

We will need the same variables except for Group ID.

Variables

And constructor is absolutely straightforward. We simply initialize Logger, bootstrap server and a topic.

Constructor

We initialize properties in the same fashion as in Part 1.

Consumer properties

And now the different part. We define the Run method with parameters — messages offset, fetching partition number and number of messages to fetch. Here we initialize a Consumer with props defined above and execute two methods — at first we setup consumer and then fetching messages.

Run Method

We start to wait and to fetch messages from the selected topic. We do this in a very imperative way just for the sake of clarity. Don’t write such code in production, please. We define a number of messages we have already fetched and it’s 0 on the beginning. Also, we define a flag to stop reading messages when it’s enough. ConsumerRecord is an object, that polls Kafka broker and we read fetched messages in a plain the for loop. Once the number of messages reaches required, we exiting the loop. That’s all.

Fetch messages

Let’s define the Main function in the class and read messages we have sent earlier in Part 1. Here 15L means a variable of a Long type. Partition number — is, well, a number of a partition to read. A number of messages — the number of messages we’re going to fetch.

Main method

The result should look something like this.

Consumer result.

The source code is available in our Github repo:

Tutorial Kafka Using Java Repo

To know more about Kafka and how to use Kafka with Java, click on links below

Apache Kafka. MacOS installation guide.

Kafka Using Java. Part 1.

Thank you for reading!

--

--

Pharos Production
Pharos Production

Published in Pharos Production

Software Development Company. Fintech and Blockchain. Enterprise Solutions.

Dmytro Nasyrov
Dmytro Nasyrov

Written by Dmytro Nasyrov

We build high-load software. Pharos Production founder and CTO.