Spring Boot Kafka Producer Example | Spring Boot KafkaTemplate

PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC
EXCEPTIONS
COLLECTIONS
SWING
JDBC
JAVA 8
SPRING
SPRING BOOT
HIBERNATE
PYTHON
PHP
JQUERY
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
In this tutorial, we are going to see how to publish Kafka messages with Spring Boot Kafka Producer.
As part of this example, we will see how to publish a simple string message to Kafka topic.
Spring Boot 2.1.3
Spring Kafka
Java 8
Maven
Install Apache Kafka on your machine, follow below articles to install Kafka.
Install Apache Kafka on Windows 10 Operating system
Install Apache Kafka on Ubuntu Operating system
root@work:/usr/local/kafka/bin# ./zookeeper-server-start.sh ../config/zookeeper.properties 
[2019-03-28 00:22:52,195] INFO Reading configuration from: ../config/zookeeper.properties (org.apache.zookeeper.server.quorum.QuorumPeerConfig)
[2019-03-28 00:22:52,210] INFO autopurge.snapRetainCount set to 3 (org.apache.zookeeper.server.DatadirCleanupManager)
[2019-03-28 00:22:52,210] INFO autopurge.purgeInterval set to 0 (org.apache.zookeeper.server.DatadirCleanupManager)
[2019-03-28 00:22:52,211] INFO Purge task is not scheduled. (org.apache.zookeeper.server.DatadirCleanupManager)
[2019-03-28 00:22:52,211] WARN Either no config or no quorum defined in config, running  in standalone mode (org.apache.zookeeper.server.quorum.QuorumPeerMain)

root@work:/usr/local/kafka/bin# ./kafka-server-start.sh ../config/server.properties 
[2019-03-28 00:24:08,203] INFO Registered kafka:type=kafka.Log4jController MBean (kafka.utils.Log4jControllerRegistration$)
[2019-03-28 00:24:09,146] INFO starting (kafka.server.KafkaServer)
[2019-03-28 00:24:09,147] INFO Connecting to zookeeper on localhost:2181 (kafka.server.KafkaServer)
[2019-03-28 00:24:09,219] INFO [ZooKeeperClient] Initializing a new session to localhost:2181. (kafka.zookeeper.ZooKeeperClient)
[2019-03-28 00:24:09,229] INFO Client environment:zookeeper.version=3.4.13-2d71af4dbe22557fda74f9a9b4309b15a7487f03, built on 06/29/2018 00:39 GMT (org.apache.zookeeper.ZooKeeper)

root@work:/usr/local/kafka/bin# ./kafka-topics.sh --create --zookeeper localhost:2181 --replication-factor 1 --partitions 1 --topic hello-topic
Created topic "hello-topic".

root@work:/usr/local/kafka/bin# ./kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic hello-topic --from-beginning

On the above pre-requisites session, we have started zookeeper, Kafka server and created one hello-topic and also started Kafka consumer console.
Now we are going to push some messages to hello-topic through Spring boot application using KafkaTemplate and we will monitor these messages from Kafka consumer console.
dependencies>
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
  </dependency>
  <dependency>
    <groupId>org.springframework.kafka</groupId>
    <artifactId>spring-kafka</artifactId>
  </dependency>
</dependencies>
Sending simple string messages to Kafka topic.
package com.onlinetutorialspoint.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("producer")
public class HelloController {

    @Autowired
    KafkaTemplate<String,String> template;
    String TOPIC_NAME = "hello-topic";

    @GetMapping("/say/{msg}")
    public String postMessage(@PathVariable("msg") String msg){
        template.send(TOPIC_NAME,msg);
        return "Message published successfully";
    }
}

package com.onlinetutorialspoint;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringBootKafkaProducerApplication {

  public static void main(String[] args) {
    SpringApplication.run(SpringBootKafkaProducerApplication.class, args);
  }

}

$ mvn clean install
$ mvn spring-boot:run
 .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.1.3.RELEASE)

2019-03-28 00:32:13.814  INFO 15921 --- [           main] c.o.SpringBootKafkaProducerApplication   : Starting SpringBootKafkaProducerApplication on work with PID 15921 (/home/cgoka/Documents/Work/Spring_Examples/Spring-Boot-Kafka-Producer/target/classes started by cgoka in /home/cgoka/Documents/Work/Spring_Examples/Spring-Boot-Kafka-Producer)
.....
.....
 
Spring Boot Kafka
KafkaTemplate
Happy Learning 🙂


Spring-Boot-Kafka-Producer

File size: 89 KB
Downloads: 708


Spring Boot How to change the Tomcat to Jetty Server
Spring Boot RabbitMQ Message Publishing Example
Sending Spring Boot Kafka JSON Message to Kafka Topic
Step By Step Spring Boot Docker Deployment Example
Spring Boot Redis Cache Example – Redis Server
SSL Spring Boot HTTPs Enabling Example
Spring Boot Kafka Consume JSON Messages Example
Install Apache Kafka on Windows 10
How to install Apache Kafka on Ubuntu 18.04
Spring Boot MongoDB + Spring Data Example
Spring Boot MVC Example Tutorials
How to Send Mail Spring Boot Example
How to set Spring Boot SetTimeZone
How to use Spring Boot Random Port
MicroServices Spring Boot Eureka Server Example

Spring Boot How to change the Tomcat to Jetty Server
Spring Boot RabbitMQ Message Publishing Example
Sending Spring Boot Kafka JSON Message to Kafka Topic
Step By Step Spring Boot Docker Deployment Example
Spring Boot Redis Cache Example – Redis Server
SSL Spring Boot HTTPs Enabling Example
Spring Boot Kafka Consume JSON Messages Example
Install Apache Kafka on Windows 10
How to install Apache Kafka on Ubuntu 18.04
Spring Boot MongoDB + Spring Data Example
Spring Boot MVC Example Tutorials
How to Send Mail Spring Boot Example
How to set Spring Boot SetTimeZone
How to use Spring Boot Random Port
MicroServices Spring Boot Eureka Server Example
 


Δ
 Spring Boot – Hello World
 Spring Boot – MVC Example
 Spring Boot- Change Context Path
 Spring Boot – Change Tomcat Port Number
 Spring Boot – Change Tomcat to Jetty Server
 Spring Boot – Tomcat session timeout
 Spring Boot – Enable Random Port
 Spring Boot – Properties File
 Spring Boot – Beans Lazy Loading
 Spring Boot – Set Favicon image
 Spring Boot – Set Custom Banner
 Spring Boot – Set Application TimeZone
 Spring Boot – Send Mail
 Spring Boot – FileUpload Ajax
 Spring Boot – Actuator
 Spring Boot – Actuator Database Health Check
 Spring Boot – Swagger
 Spring Boot – Enable CORS
 Spring Boot – External Apache ActiveMQ Setup
 Spring Boot – Inmemory Apache ActiveMq
 Spring Boot – Scheduler Job
 Spring Boot – Exception Handling
 Spring Boot – Hibernate CRUD
 Spring Boot – JPA Integration CRUD
 Spring Boot – JPA DataRest CRUD
 Spring Boot – JdbcTemplate CRUD
 Spring Boot – Multiple Data Sources Config
 Spring Boot – JNDI Configuration
 Spring Boot – H2 Database CRUD
 Spring Boot – MongoDB CRUD
 Spring Boot – Redis Data CRUD
 Spring Boot – MVC Login Form Validation
 Spring Boot – Custom Error Pages
 Spring Boot – iText PDF
 Spring Boot – Enable SSL (HTTPs)
 Spring Boot – Basic Authentication
 Spring Boot – In Memory Basic Authentication
 Spring Boot – Security MySQL Database Integration
 Spring Boot – Redis Cache – Redis Server
 Spring Boot – Hazelcast Cache
 Spring Boot – EhCache
 Spring Boot – Kafka Producer
 Spring Boot – Kafka Consumer
 Spring Boot – Kafka JSON Message to Kafka Topic
 Spring Boot – RabbitMQ Publisher
 Spring Boot – RabbitMQ Consumer
 Spring Boot – SOAP Consumer
 Spring Boot – Soap WebServices
 Spring Boot – Batch Csv to Database
 Spring Boot – Eureka Server
 Spring Boot – MockMvc JUnit
 Spring Boot – Docker Deployment