Apache Kafka – Java Producer & Consumer


Apache Kakfa is an opensource distributed event streaming platform which works based on publish/subscribe messaging system. That means, there would be a producer who publishes messages to Kafka and a consumer who reads messages from Kafka. In between, Kafka acts like a filesystem or database commit log.

In this article we will discuss about writing a Kafka producer and consumer using Java with customized serialization and deserializations.

Kakfa Producer Application:

Producer is the one who publish the messages to Kafka topic. Topic is a partitioner in Kafka environment, it is very similar to a folder in a file system. In the below example program, messages are getting published to Kafka topic ‘kafka-message-count-topic‘.

package com.malliktalksjava.kafka.producer;

import java.util.Properties;
import java.util.concurrent.ExecutionException;

import com.malliktalksjava.kafka.constants.KafkaConstants;
import com.malliktalksjava.kafka.util.CustomPartitioner;
import org.apache.kafka.clients.producer.*;
import org.apache.kafka.common.serialization.LongSerializer;
import org.apache.kafka.common.serialization.StringSerializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class KafkaSampleProducer {

    static Logger log = LoggerFactory.getLogger(KafkaSampleProducer.class);

    public static void main(String[] args) {
        runProducer();
    }

    static void runProducer() {
        Producer<Long, String> producer = createProducer();

        for (int index = 0; index < KafkaConstants.MESSAGE_COUNT; index++) {
            ProducerRecord<Long, String> record = new ProducerRecord<Long, String>(KafkaConstants.TOPIC_NAME,
                    "This is record " + index);
            try {
                RecordMetadata metadata = producer.send(record).get();
                //log.info("Record sent with key " + index + " to partition " + metadata.partition() +
                 //       " with offset " + metadata.offset());
                System.out.println("Record sent with key " + index + " to partition " + metadata.partition() +
                        " with offset " + metadata.offset());
            } catch (ExecutionException e) {
                log.error("Error in sending record", e);
                e.printStackTrace();
            } catch (InterruptedException e) {
                log.error("Error in sending record", e);
                e.printStackTrace();
            }
        }
    }

    public static Producer<Long, String> createProducer() {
        Properties props = new Properties();
        props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, KafkaConstants.KAFKA_BROKERS);
        props.put(ProducerConfig.CLIENT_ID_CONFIG, KafkaConstants.CLIENT_ID);
        props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, LongSerializer.class.getName());
        props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
        props.put(ProducerConfig.PARTITIONER_CLASS_CONFIG, CustomPartitioner.class.getName());
        return new KafkaProducer<>(props);
    }
}

Kakfa Consumer Program:

Consumer is the one who subscribe to Kafka topic to read the messages. There are different ways to read the messages from Kafka, below example polls the topic for every thousend milli seconds to fetch the messages from Kafka.

package com.malliktalksjava.kafka.consumer;

import java.util.Collections;
import java.util.Properties;

import com.malliktalksjava.kafka.constants.KafkaConstants;
import com.malliktalksjava.kafka.producer.KafkaSampleProducer;
import org.apache.kafka.clients.consumer.Consumer;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.serialization.LongDeserializer;
import org.apache.kafka.common.serialization.StringDeserializer;

import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class KafkaSampleConsumer {
    static Logger log = LoggerFactory.getLogger(KafkaSampleProducer.class);

    public static void main(String[] args) {
        runConsumer();
    }

    static void runConsumer() {
        Consumer<Long, String> consumer = createConsumer();
        int noMessageFound = 0;
        while (true) {
            ConsumerRecords<Long, String> consumerRecords = consumer.poll(1000);
            // 1000 is the time in milliseconds consumer will wait if no record is found at broker.
            if (consumerRecords.count() == 0) {
                noMessageFound++;
                if (noMessageFound > KafkaConstants.MAX_NO_MESSAGE_FOUND_COUNT)
                    // If no message found count is reached to threshold exit loop.
                    break;
                else
                    continue;
            }

            //print each record.
            consumerRecords.forEach(record -> {
                System.out.println("Record Key " + record.key());
                System.out.println("Record value " + record.value());
                System.out.println("Record partition " + record.partition());
                System.out.println("Record offset " + record.offset());
            });

            // commits the offset of record to broker.
            consumer.commitAsync();
        }
        consumer.close();
    }

        public static Consumer<Long, String> createConsumer() {
            Properties props = new Properties();
            props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, KafkaConstants.KAFKA_BROKERS);
            props.put(ConsumerConfig.GROUP_ID_CONFIG, KafkaConstants.GROUP_ID_CONFIG);
            props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, LongDeserializer.class.getName());
            props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
            props.put(ConsumerConfig.MAX_POLL_RECORDS_CONFIG, KafkaConstants.MAX_POLL_RECORDS);
            props.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "false");
            props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, KafkaConstants.OFFSET_RESET_EARLIER);

            Consumer<Long, String> consumer = new KafkaConsumer<>(props);
            consumer.subscribe(Collections.singletonList(KafkaConstants.TOPIC_NAME));
            return consumer;
        }
}

Messages will be published to a Kafka partition called Topic. A Kafka topic is sub-divided into units called partitions for fault tolerance and scalability.

Every Record in Kafka has key value pairs, while publishing messages key is optional. If you don’t pass the key, Kafka will assign its own key for each message. In Above example, ProducerRecord<Integer, String> is the message that published to Kafka has Integer type as key and String as value.

Message Model Class: Below model class is used to publish the object. Refer to below descriptions on how this class being used in the application.

package com.malliktalksjava.kafka.model;

import java.io.Serializable;

public class Message implements Serializable{

    private static final long serialVersionUID = 1L;

    private String id;
    private String name;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

Constants class: All the constants related to this application have been placed into below class.

package com.malliktalksjava.kafka.constants;

public class KafkaConstants {

    public static String KAFKA_BROKERS = "localhost:9092";

    public static Integer MESSAGE_COUNT=100;

    public static String CLIENT_ID="client1";

    public static String TOPIC_NAME="kafka-message-count-topic";

    public static String GROUP_ID_CONFIG="consumerGroup1";

    public static String GROUP_ID_CONFIG_2 ="consumerGroup2";

    public static Integer MAX_NO_MESSAGE_FOUND_COUNT=100;

    public static String OFFSET_RESET_LATEST="latest";

    public static String OFFSET_RESET_EARLIER="earliest";

    public static Integer MAX_POLL_RECORDS=1;
}

Custom Serializer: Serializer is the class which converts java objects to write into disk. Below custom serializer is converting the Message object to JSON String. Serialized message will be placed into Kafka Topic, this message can’t be read until it is deserialized by the consumer.

package com.malliktalksjava.kafka.util;

import java.util.Map;
import com.malliktalksjava.kafka.model.Message;
import org.apache.kafka.common.serialization.Serializer;
import com.fasterxml.jackson.databind.ObjectMapper;

public class CustomSerializer implements Serializer<Message> {

    @Override
    public void configure(Map<String, ?> configs, boolean isKey) {

    }

    @Override
    public byte[] serialize(String topic, Message data) {
        byte[] retVal = null;
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            retVal = objectMapper.writeValueAsString(data).getBytes();
        } catch (Exception exception) {
            System.out.println("Error in serializing object"+ data);
        }
        return retVal;
    }
    @Override
    public void close() {

    }
}

Custom Deserializer: Below custom deserializer, converts the serealized object coming from Kafka into Java object.

package com.malliktalksjava.kafka.util;

import java.util.Map;

import com.malliktalksjava.kafka.model.Message;
import org.apache.kafka.common.serialization.Deserializer;

import com.fasterxml.jackson.databind.ObjectMapper;

public class CustomObjectDeserializer implements Deserializer<Message> {

    @Override
    public void configure(Map<String, ?> configs, boolean isKey) {
    }

    @Override
    public Message deserialize(String topic, byte[] data) {
        ObjectMapper mapper = new ObjectMapper();
        Message object = null;
        try {
            object = mapper.readValue(data, Message.class);
        } catch (Exception exception) {
            System.out.println("Error in deserializing bytes "+ exception);
        }
        return object;
    }

    @Override
    public void close() {
    }
}

Custom Partitioner: If you would like to do any custom settings for Kafka, you can do that using the java code. Below is the sample custom partitioner created as part of this applicaiton.

package com.malliktalksjava.kafka.util;

import org.apache.kafka.clients.producer.Partitioner;
import org.apache.kafka.common.Cluster;
import java.util.Map;

public class CustomPartitioner implements Partitioner{

    private static final int PARTITION_COUNT=50;

    @Override
    public void configure(Map<String, ?> configs) {

    }

    @Override
    public int partition(String topic, Object key, byte[] keyBytes, Object value, byte[] valueBytes, Cluster cluster) {
        Integer keyInt=Integer.parseInt(key.toString());
        return keyInt % PARTITION_COUNT;
    }

    @Override
    public void close() {
    }
}

Here is the GIT Hub link for the program: https://github.com/mallikarjungunda/kafka-producer-consumer

Hope you liked the details, please share your feedback in comments.

Create a Java web service using top down approch


In the bottom up approach, we will write the java class and generates the WSDL file and other dependent components. The same will be deployed into the web containers.

In Top down approach, Architects will write the WSDL file based on the requirements. Developer need to make the corresponding service implementation using the WSDL provided. This post will explain how to create a service using the WSDL file.

Step 1: Create a dynamic or java project as mentioned here

Here, I have created a sample web dynamic project with the name SampleWS as given below.

Dyanmic web project

Step 2: generate the service using top down approach

Right click on the SamplWS project name -> New -> Other

SelectOther

Select the Web Service from the wizard as below and click on Finish button.

select webservice

Select the Web service type as ‘Top down Java bean Web service’ and provide the WSDL url in the Service definition drop down and click on Finish button.

Sample WSDL URL is: http://localhost:8080/SampleWebService/wsdl/Calculator.wsdl

providethewsdl

Your Web service is ready with the Java bean methods as below and the Final folder structure looks like below:

service Folder structure

Write the business logic into the Service class as given below:

Generated class:

/**
* CalculatorSoapBindingImpl.java
*
* This file was auto-generated from WSDL
* by the Apache Axis 1.4 Apr 22, 2006 (06:55:48 PDT) WSDL2Java emitter.
*/

package in.malliktalksjava;

public class CalculatorSoapBindingImpl implements in.malliktalksjava.Calculator{
public int addition(int var1, int var2) throws java.rmi.RemoteException {
return -3;
}

public int multiplication(int var1, int var2) throws java.rmi.RemoteException {
return -3;
}

public int division(int var1, int var2) throws java.rmi.RemoteException {
return -3;
}

}

Implemented class:

/**
* CalculatorSoapBindingImpl.java
*
* This file was auto-generated from WSDL
* by the Apache Axis 1.4 Apr 22, 2006 (06:55:48 PDT) WSDL2Java emitter.
*/

package in.malliktalksjava;

public class CalculatorSoapBindingImpl implements in.malliktalksjava.Calculator{
public int addition(int var1, int var2) throws java.rmi.RemoteException {
return var1+var2;
}

public int multiplication(int var1, int var2) throws java.rmi.RemoteException {
return var1*var2;
}

public int division(int var1, int var2) throws java.rmi.RemoteException {
return var1/var2;
}

}

Deploy the application into server and use the below url as a WSDL for this to have the client.

http://localhost:8080/SampleWebService/wsdl/Calculator.wsdl

 

Other Useful Links:

 Click here to know more about webservices

Click here to know more about RESTfull web services.

Click here for Web services Question and Answers.

Click here to know how to write web service client suing java.

Write a Client for web service


Below steps explains how to write a web service client in java using STS IDE.

Step 1: Create a Java project using the steps mentioned here.

Step 2: Generate the stubs for the Java web service using below steps

Mouse Right click on Client project and select New -> Other

select other option

Select the Web service client from the wizard

Select webservice cliet

Provide the service WSDL url in the Service Definition text box and click on finish button.

Enterwsdl into service defination

Web service client stubs will be generated into the package and final folder structure looks below.

Client stubs generated

Write the Client class using the stubs and test the client project.

Write a client

 

Use the below sample code to write the client:

 

package in.malliktalksjava.client;

import java.rmi.RemoteException;

import in.malliktalksjava.Calculator;
import in.malliktalksjava.CalculatorServiceLocator;
import javax.xml.namespace.QName;
import javax.xml.rpc.ServiceException;

/**
* @author Javatutorials
* @since version 1.0
*
*/
public class SampleWSClient {

/**
* @param args
*/
public static void main(String[] args) {

SampleWSClient sc = new SampleWSClient();
sc.callCalculatorWebservice();
}

/**
* used to call web service
*/
public void callCalculatorWebservice(){

String wsdl = “http://localhost:8080/SampleWebService/wsdl/Calculator.wsdl&#8221;;
QName queue = new QName(“http://malliktalksjava.in&#8221;, “CalculatorService”);

try {
//create the servicelocator object
CalculatorServiceLocator calServiceLoc = new CalculatorServiceLocator(wsdl, queue);
//create the service object
Calculator calculator = calServiceLoc.getCalculator();
//call the service methods
System.out.println(“addition result : “+calculator.addition(10, 11));
System.out.println(“division result : “+calculator.division(10, 5));
System.out.println(“multiplication result : “+calculator.multiplication(10, 10));
} catch (ServiceException e) {
e.printStackTrace();
} catch (RemoteException e) {
e.printStackTrace();
}
}
}

 

With this your client application is ready to use.

 

Other Useful links:

Click here to know how to create the web service project.

Click here to know the difference between SOAP and RESTfull web services.

Create a java webservice using STS


Below steps explains the how to create a web-service in java in bottom-up approach using the STS(Spring tool suite) IDE. In the bottom-up approach, first we will create a template class, using the template class we will generate the WSDL and deploy the service in servers. Follow the below steps to create a webservice.

Step 1: Create a new java project using the steps mentioned here

Step 2 : Create a template Java class as service

Create a Java class in src folder of the in.javatutorials package as below

Writeaclass

Provide the package name and class name into respective fields and click on finish button.

Namethetheclass

Implement the Java methods as give below:

write the class

Use the below source code to write the class:

package in.malliktalksjava;

/**
* Calculator class exposed as a webservice
* @author malliktalksjava
* @since Version 1.0
*
*/
public class Calculator {

/**
* adds the two input parameters and return the result
* @param var1
* @param var2
* @return
*/
public Integer addition(int var1, int var2) {

Integer result = var1 + var2;
System.out.println(“addition result in service : ” + result);
return result;
}

/**
* multiply the two input parameters and return the result
* @param var1
* @param var2
* @return
*/
public Integer multiplication(int var1, int var2) {

Integer result = var1 * var2;
System.out.println(“multiplication result in service : ” + result);
return result;
}

/**
* divide the two input parameters and return the result
* @param var1
* @param var2
* @return
*/
public Integer division(int var1, int var2) {

Integer result = var1 / var2;
System.out.println(“division result in service : ” + result);
return result;
}

}

Step 3: make the java class as web service

Select the Java class as below

maketheclassas service

Choose Web Service from the  and click on Next button

createservice

Select the ‘Bottom up Java bean Web Service’  from the Web service type and service implementation class as mentioned in the below picture and click on Next button.

bottomup webservice

Select the service methods from the menu and click on Finish button. The Service implementation style used is document/literal as shown in below picture.

choose service methods

The folder structure of the web application looks like below:

webservice folder structure

Deploy the service into tomcat web server and access the WSDL file using the below url:

http://localhost:8080/SampleWebService/wsdl/Calculator.wsdl

wsdlfile

Finally your web service is ready to use and WSDL url is the end point url for your web service.

 

Other Useful links:

 Click here to know more about webservices

Click here to know more about RESTfull web services.

Click here for Web services Question and Answers.

Click here to know how to write web service client suing java.

What are the differences between SOAP WS and RESTful WS?


SOAP Web Services RESTfull Web Services
The SOAP WS supports both remote procedure call (i.e. RPC) and message oriented middle-ware (MOM) integration styles. The Restful Web Service supports only RPC integration style.
The SOAP WS is transport protocol neutral. Supports multiple protocols like HTTP(S),  Messaging, TCP, UDP SMTP, etc. The REST is transport protocol specific. Supports only HTTP or HTTPS protocols.
The SOAP WS permits only XML data format. You define operations, which tunnels through the POST. The focus is on accessing the named operations and exposing the application logic as a service. The REST permits multiple data formats like XML, JSON data, text, HTML, etc. Any browser can be used because the REST approach uses the standard GET, PUT, POST, and DELETE Web operations. The focus is on accessing the named resources and exposing the data as a service. REST has AJAX support. It can use the XMLHttpRequest object. Good for stateless CRUD (Create, Read, Update, and Delete) operations.GET – represent()POST – acceptRepresention()

PUT – storeRepresention()

DELETE – removeRepresention()

SOAP based reads cannot be cached. REST based reads can be cached. Performs and scales better.
SOAP WS supports both SSL security and WS-security, which adds some enterprise security features like maintaining security right up to the point where it is needed, maintaining identities through intermediaries and not just point to point SSL only, securing different parts of the message with different security algorithms, etc. The REST supports only point-to-point SSL security. The SSL encrypts the whole message, whether all of it is sensitive or not.
The SOAP has comprehensive support for both ACID based transaction management for short-lived transactions and compensation based transaction management for long-running transactions. It also supports two-phase commit across distributed resources. The REST supports transactions, but it is neither ACID compliant nor can provide two phase commit across distributed transactional resources as it is limited by its HTTP protocol.
The SOAP has success or retries logic built in and provides end-to-end reliability even through SOAP intermediaries. REST does not have a standard messaging system, and expects clients invoking the service to deal with communication failures by retrying.

 

Other Useful links:

 Click here to know more about webservices

Click here to know more about RESTfull web services.

Click here for Web services Question and Answers.

Click here to know how to create a SOAP web service.

Click here to know how to write web service client suing java.

WEB Services Interview Questions


1)What is web Services ?
Getting the services through the web.

2)What is JAX-RPC?
JAX-RPC means java api for xml based RPC is a java api for developing and using web-services.
An RPC based web-service is a collection of procedures that can be called by remote client over the internet.
Ex: A typical RPC based web service is a stock quote service that takes a SOAP request for the price of a specified stock and returns the price via SOAP.

3)Explain about Web Services
A Web service, a server application that implements the procedures that available for clients to call, deployed on server-side container.
A web service can make itself available to potential clients by describing itself in a Web Service Description Language (WSDL) document.

4)What is WSDL?
WSDL is an XML document that gives all pertinent information about web service, the operation that can be called on it, parameters for those operations, and the location of where to send requests.
A web client can use WSDL document to discover the what the service offers and how to access it.

5)Explain some of the features of the web services?
Some of the features of the web services are:
1.Interoperability
Using JAX-RPC, a client written in a language other than Java programming language can access a web service developed and deployed on the Java platform. Conversely,a client written in the Java programming language can communicate with a service that was developed and deployed using some other platform.
2.Ease of use:
Using JAX-RPC makes the user to feel comfortable over the RPC. The internal complicated infrastructure, like marshaling, unmarshaling, and transmission details..etc, will be taken care automatically.
3.Advanced features

6)What makes interoperability is possible?
JAX-RPC support for SOAP and WSDL.

7)What is JAXM?
Java API for Messaging provides a standard way to send XML documents over the Internet from the Java platform. It is based on SOAP 1.1 and SOAP with attachments specifications, which define a basic framework for exchanging XML messages.
8)The features of JAXM over the RPC including JAX-RPC
a) One way(asynchronous)messaging.
b) Routing of message to more than one party.
c) Reliable messaging features such as guarantied delivery.

9)What is JAXR?
Java API for XML registries provides a convenient way to access standard business registries over the Internet. Using JAXR one can register the business registry and one can search for a business registry for other business.

10) What tools do you use to test your Web Services?

 SoapUI tool for SOAP WS and the Firefox “poster” plugin for RESTFul services.

11) What is the difference between SOA and a Web service? 

SOA is a software design principle and an architectural pattern for implementing loosely coupled, reusable and coarse grained services. You can implement SOA using any protocols such as HTTP, HTTPS, JMS, SMTP, RMI, IIOP (i.e. EJB uses IIOP), RPC etc. Messages can be in XML or Data Transfer Objects (DTOs).

Web service is an implementation technology and one of the ways to implement SOA. You can build SOA based applications without using Web services – for example by using other traditional technologies like Java RMI, EJB, JMS based messaging, etc. But what Web services offer is the standards based  and platform-independent service via HTTP, XML, SOAP, WSDL and UDDI, thus allowing interoperability between heterogeneous technologies such as J2EE and .NET.