├── .gitignore ├── LICENSE ├── README.md ├── pom.xml └── src ├── main ├── java │ └── com │ │ └── ay │ │ └── testlab │ │ └── kafka │ │ ├── Application.java │ │ ├── KafkaConsumerConfig.java │ │ ├── KafkaProducerConfig.java │ │ ├── batchlistener │ │ ├── BatchMessageConsumer.java │ │ ├── BatchMessageConsumingExample.java │ │ └── MessageProducerForBatchListener.java │ │ ├── multipartition │ │ ├── MultiPartitionMessageConsumer.java │ │ ├── MultiPartitionMessageProducer.java │ │ └── MultiPartitionMessagingExample.java │ │ ├── rest │ │ └── SimpleController.java │ │ ├── simplemessage │ │ ├── SimpleKafkaMessageConsumer.java │ │ ├── SimpleKafkaMessageProducer.java │ │ └── SimpleKafkaMessagingExample.java │ │ └── streamapi │ │ ├── KafkaStreamExample.java │ │ ├── SimpleKafkaMessageConsumerForStreaming.java │ │ ├── SimpleKafkaMessageProducerForStreaming.java │ │ └── SimpleKafkaStream.java └── resources │ └── application.yml └── test ├── java └── com │ └── ay │ └── testlab │ └── kafka │ └── SimpleKafkaMessageTest.java └── resources └── application.yml /.gitignore: -------------------------------------------------------------------------------- 1 | .idea 2 | target 3 | *.iml 4 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # kafka-with-springboot 2 | Demonstrations for Kafka with Spring Boot 3 | 4 | This project is created for starting Kafka based project much faster by providing simple example applications for different scenarios. It may also be used as a tutorial for those who likes learning by playing with codes. :) 5 | 6 | ### 1. Kafka Setup: 7 | - Download Kafka from 8 | - Start Zookeper server with default configuration file (localhost:2181) 9 | ```bash 10 | > ./bin/zookeeper-server-start.sh ./config/zookeeper.properties 11 | ``` 12 | - Start Kafka Server with default configuration file as single-broker cluster (localhost:9092) 13 | ```bash 14 | > ./bin/kafka-server-start.sh ./config/server.properties 15 | ``` 16 | (Windows users can use bash scripts under ./bin/windows folder) 17 | 18 | ### 2. Application Configuration Notes 19 | - For each example, just activate related commented lines in *Application.java*. 20 | - Spring boot can inject properties from YAML files by default when they are defined in resource/application.yml. Properties like Kafka initial lookup server address, topic names, and etc. are defined there. 21 | - KafkaProducerConfig and KafkaConsumerConfig classes contains base configurations for Kafka. 22 | - There is also a dummy rest controller, if you wish to play with Kafka in rest calls. 23 | 24 | ### 3. Simple Kafka Messaging Example 25 | First Create a test topic to use with the example. 26 | ```bash 27 | > ./bin/kafka-topics.sh --create --topic kafkaSimpleMessageTopic --bootstrap-server localhost:9092 --replication-factor 1 --partitions 1 28 | ``` 29 | 30 | In the simplemessage package, a message consume/produce example is implemented. In SimpleKafkaMessaging class, we send 100 consecutive messages to Kafka with our producer. Then these messages are consumed by our consumer which subscribes to Kafka server during initialization. Producer and Consumer classes are given below. 31 | ```java 32 | public class SimpleKafkaMessageProducer { 33 | 34 | private static final Logger LOGGER = LoggerFactory.getLogger(SimpleKafkaMessageProducer.class); 35 | 36 | @Autowired 37 | private KafkaTemplate kafkaTemplate; 38 | 39 | public void send(String topic, String payload){ 40 | LOGGER.info("Sending payload='{}' to topic='{}'", payload, topic); 41 | kafkaTemplate.send(topic, payload); 42 | } 43 | } 44 | ``` 45 | For sending messages, KafkaTemplate is used. KafkaTemplate is a wrapper for Producer api. It simplifies sending data to kafka topics. 46 | 47 | ```java 48 | public class SimpleKafkaMessageConsumer { 49 | 50 | private static final Logger LOGGER = LoggerFactory.getLogger(SimpleKafkaMessageConsumer.class); 51 | 52 | @KafkaListener(topics = "${kafka.topic.simpleMessageTopic}") 53 | public void receive(String payload) { 54 | LOGGER.info("Received payload='{}'", payload); 55 | } 56 | } 57 | ``` 58 | For consuming messages, we just use @KafkaListener annotation with the suitable topic name. @KafkaListener annotation defines consumer methods for Kafka topics. Note that, We also use @EnableKafka annotation in KafkaConsumerConfig configuration class. It enables auto detection of @KafkaListener annotations on any Spring-managed bean in the container. 59 | 60 | ### 4. Multi-Partition Messaging Example 61 | This example will demonstrate usage of Kafka with multi-partitioned topic with two consumer groups. 62 | 63 | For this example, we first create a new topic "kafkaMultiPartitionTopic" with 3 partitions and also add it to our application.yml file under resource folder. 64 | ```bash 65 | > ./bin/kafka-topics.sh --create --topic kafkaMultiPartitionTopic --bootstrap-server localhost:9092 --replication-factor 1 --partitions 3 66 | ``` 67 | Now we have a new topic with 3 partitions. In this example, we'll make a little change to our message sending method in producer class to control partition selection logic; 68 | 69 | Here, *kafkaTemplate* requires another parameter called *key*. Kafka uses this parameter as an input to its hash function to determine which partition is assigned for message. Kafka guarantees that messages with the same key value will be assigned to the same partition. 70 | 71 | We also add success and failure callbacks here for debugging purpose. These callbacks return valuable information after message is retrieved by Kafka server. 72 | ```java 73 | public class MultiPartitionMessageProducer { 74 | //... 75 | public void send(String topic, String key, String payload){ 76 | LOGGER.info("Sending payload='{}' to topic='{}' with key='{}'", payload, topic, key); 77 | ListenableFuture> future = kafkaTemplate.send(topic, key ,payload); 78 | SuccessCallback> successCallback = sendResult -> { 79 | LOGGER.info("Sent payload='{}' with key='{}' to topic-partition@offset='{}'", payload, key, sendResult.getRecordMetadata().toString()); 80 | }; 81 | FailureCallback failureCallback = throwable -> { 82 | LOGGER.info("Sending payload='{}' to topic='{}' with key='{}' failed!!!", payload, topic, key); 83 | }; 84 | future.addCallback(successCallback, failureCallback); 85 | } 86 | //... 87 | } 88 | ``` 89 | Next, lets define our consumers. This time, we'll create two consumer groups. 90 | 91 | First consumer group consists of two different consumers (receiver1a and receiver1b). Since we have 3 partitions, Kafka will assign two partitions to one consumer and one partition to the other one. 92 | 93 | Second consumer group contains 6 consumer threads which'll call same listener method (receive2). This time, we create consumers by setting concurrency level of ListenerContainer. As a result, all our consumers'll call same listener method with multi-thread way. I have used concurrency just to see how different it'' work. It differs only in multi-thread nature and all consumers works in the same listener container. 94 | 95 | The important point in this example is that, if the number of consumers are less than number of partitions then some partitions will be assigned to the same consumers. If there are equal number of partitions and consumers then each consumer will handle one partition. Finally, if consumers are high in number then some of them will be idle and only be there for high availability. 96 | 97 | While defining our consumers, we set consumer group name by *groupId* parameter. Number of consumers are defined in *containerFactory* by setting concurreny level. For this example, different containerFactory beans with different concurrency are created in KafkaConsumerConfig class.: 98 | ```java 99 | public class MultiPartitionMessageConsumer { 100 | 101 | private static final Logger LOGGER = LoggerFactory.getLogger(MultiPartitionMessageConsumer.class); 102 | 103 | @KafkaListener(topics = "${kafka.topic.multiPartitionTopic}", groupId = "multiPartitionWith2Consumer") 104 | public void receiver1a(@Payload String payload, 105 | @Header(KafkaHeaders.RECEIVED_PARTITION_ID)Long partitionId, 106 | @Header(KafkaHeaders.OFFSET)Long offset) { 107 | LOGGER.info("Received consumer=1a group=multiPartitionWith2Consumer payload='{}' from partitionId@offset='{}'", payload, partitionId+"@"+offset); 108 | } 109 | 110 | @KafkaListener(topics = "${kafka.topic.multiPartitionTopic}", groupId = "multiPartitionWith2Consumer") 111 | public void receiver1b(@Payload String payload, 112 | @Header(KafkaHeaders.RECEIVED_PARTITION_ID)Long partitionId, 113 | @Header(KafkaHeaders.OFFSET)Long offset) { 114 | LOGGER.info("Received consumer=1b group=multiPartitionWith2Consumer payload='{}' from partitionId@offset='{}'", payload, partitionId+"@"+offset); 115 | } 116 | 117 | @KafkaListener(topics = "${kafka.topic.multiPartitionTopic}", containerFactory = "kafkaListenerContainerFactoryWith6Consumer", groupId = "multiPartitionWithSingleConsumer6Thread") 118 | public void receive2(@Payload String payload, 119 | @Header(KafkaHeaders.RECEIVED_PARTITION_ID)Long partitionId, 120 | @Header(KafkaHeaders.OFFSET)Long offset) { 121 | LOGGER.info("Received consumer=2 group=multiPartitionWithSingleConsumer6Thread payload='{}' from partitionId@offset='{}'", payload, partitionId+"@"+offset); 122 | } 123 | } 124 | ``` 125 | 126 | ### 5. Batch Message Consuming Example 127 | This example will demonstrate usage of Kafka in batch mode. That is; consumers consume messages not one by one but as a group. 128 | 129 | Lets first create a new topic "kafkaBatchConsumerTopic" and again add it to our application.yml file under resource folder. 130 | ```bash 131 | > ./bin/kafka-topics.sh --create --topic kafkaBatchConsumerTopic --bootstrap-server localhost:9092 --replication-factor 1 --partitions 1 132 | ``` 133 | 134 | I will use a simple message producer in this example, what we will change here is only consumer part. Our consumer should be configured and implemented in a way that it can handle multiple message at a time. First lets take a look at configuration part. 135 | 136 | In KafkaConsumerConfig class, we create a new KafkaListenerContainerFactory which can create listeners for batch operations. This is done by *batchListener* property of our factory as follows: 137 | 138 | ```java 139 | @Configuration 140 | @EnableKafka 141 | public class KafkaConsumerConfig { 142 | 143 | //.... 144 | 145 | @Bean(name = "kafkaListenerContainerFactoryForBatchConsumer") 146 | public KafkaListenerContainerFactory> kafkaListenerContainerFactoryForBatchConsumer() { 147 | ConcurrentKafkaListenerContainerFactory factory = new ConcurrentKafkaListenerContainerFactory<>(); 148 | factory.setConcurrency(1); 149 | factory.setBatchListener(true); 150 | factory.setConsumerFactory(consumerFactory()); 151 | return factory; 152 | } 153 | 154 | //.... 155 | } 156 | ``` 157 | 158 | Now our consumer can receive more than one records. The number of records received is dynamically calculated in our configuration. It is also possible to set an upper limit for that. This can be done by setting *MAX_POLL_RECORDS_CONFIG* property on *ConsumerConfig* configuration. 159 | 160 | After than, consumer implementation should only be updated to receive list of messages as parameters as follows: 161 | 162 | ```java 163 | 164 | public class BatchMessageConsumer { 165 | 166 | private static final Logger LOGGER = LoggerFactory.getLogger(BatchMessageConsumer.class); 167 | 168 | @KafkaListener(topics = "${kafka.topic.batchConsumerTopic}", containerFactory = "kafkaListenerContainerFactoryForBatchConsumer", groupId = "batchConsumer") 169 | public void receive(@Payload List payloads, 170 | @Header(KafkaHeaders.RECEIVED_PARTITION_ID) List partitionIds, 171 | @Header(KafkaHeaders.OFFSET) List offsets) { 172 | LOGGER.info("Received group=batchConsumer with batch group data: "); 173 | for (int i = 0; i< payloads.size(); ++i) { 174 | LOGGER.info("---------------- payload='{}' from partitionId@offset='{}'", payloads.get(i), partitionIds.get(i)+"@"+offsets.get(i)); 175 | } 176 | 177 | } 178 | } 179 | 180 | ``` 181 | 182 | ## 6. Kafka Streams Api Example 183 | 184 | For using Kafka Streams, we need to first add kafka-streams library to our project. 185 | Note: kafka-streams doesn't work on windows platform because of a bug in 2.6.1 release. Either use 2.6.0 or wait for 2.6.2... 186 | ```xml 187 | 188 | org.apache.kafka 189 | kafka-streams 190 | 2.6.1 191 | 192 | ``` 193 | For this example, we will create a scenario where producer will send message to a topic. Than our kafka stream code will read streams of data, process it and send it to another topic. Finally our consumer will get processed data and do its job. 194 | 195 | Lets start with creation of two topics one for raw data and another one for processed data. 196 | 197 | ```bash 198 | > ./bin/kafka-topics.sh --create --zookeeper localhost:2181 --replication-factor 1 --partitions 3 --topic kafkaStreamRawDataTopic 199 | > ./bin/kafka-topics.sh --create --zookeeper localhost:2181 --replication-factor 1 --partitions 3 --topic kafkaStreamProcessedDataTopic 200 | ``` 201 | 202 | Then we will create a simple producer that sends data to *kafkaStreamRawDataTopic* and a simple consumer that reads data from *kafkaStreamProcessedDataTopic*. 203 | 204 | Now we can talk about stream processing code block which; in our case, is *SimpleKafkaStream.java*. In our stream class we should define *@EnableKafkaStream* annotation with *@Configuration* annotation by which kafka-streams can declare some beans like StreamBuilder in the application context automatically. 205 | 206 | After then, we define config method for connecting our stream code to Kafka and implement our stream processing method. In this example we just reverse the string stream data and push it to another topic. As final note; in our configuration bean, we set bean name to *DEFAULT_STREAMS_CONFIG_BEAN_NAME*. By this way, Spring Boot'll inject default StreamBuilder. Otherwise, we should also create a StreamBuilder bean along with our configuration bean. 207 | 208 | ```java 209 | @Configuration 210 | @EnableKafka 211 | @EnableKafkaStreams 212 | public class SimpleKafkaStream { 213 | 214 | private static final Logger LOGGER = LoggerFactory.getLogger(SimpleKafkaStream.class); 215 | 216 | @Value("${kafka.bootstrap-servers}") 217 | private String bootstrapServers; 218 | 219 | @Value("${kafka.topic.streamRawDataTopic}") 220 | private String rawDataTopic; 221 | 222 | @Value("${kafka.topic.streamProcessedDataTopic}") 223 | private String processedDataTopic; 224 | 225 | @Bean(name = KafkaStreamsDefaultConfiguration.DEFAULT_STREAMS_CONFIG_BEAN_NAME) 226 | public StreamsConfig kafkaStreamsConfigs() { 227 | Map props = new HashMap<>(); 228 | props.put(StreamsConfig.APPLICATION_ID_CONFIG, "simpleKafkaStream"); 229 | props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers); 230 | props.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass().getName()); 231 | props.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, Serdes.String().getClass().getName()); 232 | props.put(StreamsConfig.DEFAULT_TIMESTAMP_EXTRACTOR_CLASS_CONFIG, WallclockTimestampExtractor.class.getName()); 233 | return new StreamsConfig(props); 234 | } 235 | 236 | @Bean 237 | public KStream kafkaStream(StreamsBuilder kStreamBuilder) { 238 | KStream stream = kStreamBuilder.stream(rawDataTopic); 239 | 240 | //process messages (reverse order) 241 | stream.mapValues(messageValue -> { 242 | LOGGER.info("Stream:SimpleKafkaStream processing payloads='{}'", messageValue); 243 | return new StringBuilder(messageValue).reverse().toString(); 244 | }).to(processedDataTopic); 245 | 246 | LOGGER.info("Stream started here..."); 247 | return stream; 248 | } 249 | } 250 | 251 | ``` 252 | 253 | ## 7. Kafka Connect Api Example 254 | Kafka connect api provides data read/write interfaces between different data sources (file, database, cloud, etc.) and Kafka topics. It can be used just by injecting configuration files to Kafka Server. It is also possible to use it by implementing our own Kafka connect api based applications. We'll try both of them. 255 | #### Connect api with configuration files 256 | For configuration based example, we will work on file based connectors since no setup required. Default configuration files under the Kafka config folder can be used as base configuration. In our example, we'll read from file to a topic then process messages with our kafka stream that we have implemented in the previous example. Finally, our second connector will write processed messages into another file. 257 | 258 | Let's start with configuring our data reader (source connector). 259 | 260 | connect-file-source.properties 261 | ```properties 262 | # Unique name for the connector. Attempting to register again with the same name will fail. 263 | name=local-file-source 264 | # The Java class for the connector 265 | connector.class=FileStreamSource 266 | # The maximum number of tasks that should be created for this connector. The connector may create fewer tasks if it cannot achieve this level of parallelism. 267 | tasks.max=1 268 | # source filename 269 | file=sourceData.txt 270 | # topic where read data will be sent 271 | topic=kafkaStreamRawDataTopic 272 | # messages can also be modified with transformations like below: (this transform adds a field and its value to each message) 273 | # transforms=InsertSource 274 | # transforms.InsertSource.type=org.apache.kafka.connect.transforms.InsertField$Value 275 | # transforms.InsertSource.static.field=data_source 276 | # transforms.InsertSource.static.value=test-file-source 277 | ``` 278 | After reading data from file and sending messages to *kafkaStreamRawDataTopic*, Kafka stream application'll process messages and send them to *kafkaStreamProcessedDataTopic*. Then lets configure our data writer (sink connector) 279 | 280 | connect-file-sink.properties 281 | ```properties 282 | # Unique name for the connector. Attempting to register again with the same name will fail. 283 | name=local-file-sink 284 | # The Java class for the connector 285 | connector.class=FileStreamSink 286 | # The maximum number of tasks that should be created for this connector. The connector may create fewer tasks if it cannot achieve this level of parallelism. 287 | tasks.max=1 288 | # source filename 289 | file=sinkData.txt 290 | # topic where messages are retrieved in order to write 291 | topic=kafkaStreamProcessedDataTopic 292 | ``` 293 | Now our sink connector read messages from topic *kafkaStreamProcessedDataTopic* and write them to the *sinkData.txt* file. 294 | 295 | One more configuration file is required for defining environment properties like server address, converter types, etc. 296 | 297 | connect-file-standalone.properties 298 | ```properties 299 | bootstrap.servers=localhost:9092 300 | # The converters specify the format of data in Kafka and how to translate it into Connect data. Every Connect user will 301 | # need to configure these based on the format they want their data in when loaded from or stored into Kafka 302 | key.converter=org.apache.kafka.connect.storage.StringConverter 303 | value.converter=org.apache.kafka.connect.storage.StringConverter 304 | # Converter-specific settings can be passed in by prefixing the Converter's setting with the converter we want to apply 305 | # it to 306 | key.converter.schemas.enable=true 307 | value.converter.schemas.enable=true 308 | ``` 309 | 310 | Finally, we can start our connectors by injecting configuration files to Kafka. Note that, we can inject any number of connectors with the following command 311 | ```bash 312 | > ./bin/connect-standalone.sh config/connect-standalone.properties config/connect-file-source.properties config/connect-file-sink.properties 313 | ``` 314 | (Don't forget to add some data to *sourceData.txt file* to see the result) 315 | 316 | #### Connect api with programmatic implementation 317 | Same configuration can also be implemented programmatically with Kafka Connect api. There are two group of classes to implement: *SourceConnector* / *SinkConnector* and *SourceTask* / *SinkTask*. These can be used to implement our own connectors. 318 | 319 | "Connectors do not perform any data copying themselves: their configuration describes the data to be copied, and the Connector is responsible for breaking that job into a set of Tasks that can be distributed to workers. These Tasks also come in two corresponding flavors: SourceTask and SinkTask. With an assignment in hand, each Task must copy its subset of the data to or from Kafka..." (from documentation) 320 | 321 | There is currently no Spring Boot integration. Also writing our own connectors seems to be a little bit complex according to configuration based ones. Therefore, I am not planning to implement an example for now. Those who want to try can use 322 | 323 | 324 | ### - Extra: Unit Testing with Embedded Kafka Server 325 | 326 | *spring-kafka-test* library includes an embedded kafka server which can be used in testing our kafka dependent application logic. In order to use it, first we should add testing libraries (spring-boot-starter-test and spring-kafka-test) to maven pom file. 327 | 328 | Next we'll create a new application.yml file under test resources folder for use with test cases. We'll set our server address and also test topic name here. Note that, embedded kafka server is started on a random port. Therefore, we are using the *spring.embedded.kafka.brokers* property as server address. This property is set by the KafkaEmbedded class which we will use to start embedded kafka server. 329 | ```yaml 330 | kafka: 331 | bootstrap-servers: ${spring.embedded.kafka.brokers} 332 | topic: 333 | simpleMessageTopic: testingTopic 334 | ``` 335 | 336 | KafkaEmbedded class is annotated with @ClassRule. It starts Kafka server on a random port before test cases starts. It gets three arguments. These are number of servers, whether controlled server shutdown is required or not, and topic names on servers. Our simple test case is as follows: 337 | 338 | ```java 339 | @RunWith(SpringRunner.class) 340 | @SpringBootTest 341 | @DirtiesContext 342 | @ActiveProfiles("test") 343 | public class SimpleKafkaMessageTest { 344 | 345 | @Value("${kafka.topic.simpleMessageTopic}") 346 | private String topicName; 347 | 348 | @Autowired 349 | private SimpleKafkaMessageProducer sender; 350 | 351 | @Autowired 352 | private SimpleKafkaMessageConsumer consumer; 353 | 354 | @ClassRule 355 | public static KafkaEmbedded kafkaEmbedded = new KafkaEmbedded(1,false, "testingTopic"); 356 | 357 | @Test 358 | public void testSendReceive() throws Exception { 359 | sender.send(topicName, "test Message"); 360 | TimeUnit.SECONDS.sleep(1); 361 | Assert.assertEquals("test Message", consumer.message()); 362 | } 363 | } 364 | ``` 365 | ### - Extra Kafka Monitoring Tools (Open Source) 366 | - [Kafka Manager](https://github.com/yahoo/CMAK) - The most known one, but seems not maintained for a while. 367 | - [Kafdrop](https://github.com/obsidiandynamics/kafdrop) - The next popular one. 368 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | com.ay.testlab 8 | kafka-with-springboot 9 | 0.2 10 | 11 | 12 | org.springframework.boot 13 | spring-boot-starter-parent 14 | 2.4.3 15 | 16 | 17 | 18 | 11 19 | 20 | 21 | 22 | 23 | org.springframework.boot 24 | spring-boot-starter-web 25 | 26 | 27 | org.springframework.boot 28 | spring-boot-starter-test 29 | test 30 | 31 | 32 | org.springframework.kafka 33 | spring-kafka 34 | 2.6.6 35 | 36 | org.apache.kafka 37 | kafka-streams 38 | 2.6.0 39 | 40 | 41 | org.springframework.kafka 42 | spring-kafka-test 43 | 2.6.6 44 | test 45 | 46 | 47 | org.junit.jupiter 48 | junit-jupiter-engine 49 | 5.1.0 50 | test 51 | 52 | 53 | -------------------------------------------------------------------------------- /src/main/java/com/ay/testlab/kafka/Application.java: -------------------------------------------------------------------------------- 1 | package com.ay.testlab.kafka; 2 | 3 | import com.ay.testlab.kafka.batchlistener.BatchMessageConsumingExample; 4 | import com.ay.testlab.kafka.multipartition.MultiPartitionMessagingExample; 5 | import com.ay.testlab.kafka.simplemessage.SimpleKafkaMessagingExample; 6 | import com.ay.testlab.kafka.streamapi.KafkaStreamExample; 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.boot.CommandLineRunner; 9 | import org.springframework.boot.SpringApplication; 10 | import org.springframework.boot.autoconfigure.SpringBootApplication; 11 | import org.springframework.context.annotation.Bean; 12 | import org.springframework.context.annotation.Profile; 13 | 14 | @SpringBootApplication 15 | public class Application { 16 | 17 | public static void main(String[] args) { 18 | SpringApplication.run(Application.class, args); 19 | } 20 | 21 | @Autowired 22 | private SimpleKafkaMessagingExample simpleKafkaMessagingExample; 23 | 24 | @Autowired 25 | private MultiPartitionMessagingExample multiPartitionMessagingExample; 26 | 27 | @Autowired 28 | private BatchMessageConsumingExample batchMessageConsumingExample; 29 | 30 | @Autowired 31 | private KafkaStreamExample kafkaStreamExample; 32 | 33 | @Bean 34 | @Profile("!test") 35 | public CommandLineRunner batchMessageConsumerRunner() { 36 | return args -> { 37 | //Just comment out the examples to run 38 | //simpleKafkaMessagingExample.execute(); 39 | //multiPartitionMessagingExample.execute(); 40 | //batchMessageConsumingExample.execute(); 41 | //kafkaStreamExample.execute(); 42 | }; 43 | } 44 | } -------------------------------------------------------------------------------- /src/main/java/com/ay/testlab/kafka/KafkaConsumerConfig.java: -------------------------------------------------------------------------------- 1 | package com.ay.testlab.kafka; 2 | 3 | import org.apache.kafka.clients.consumer.ConsumerConfig; 4 | import org.apache.kafka.common.serialization.StringDeserializer; 5 | import org.springframework.beans.factory.annotation.Value; 6 | import org.springframework.context.annotation.Bean; 7 | import org.springframework.context.annotation.Configuration; 8 | import org.springframework.context.annotation.Primary; 9 | import org.springframework.kafka.annotation.EnableKafka; 10 | import org.springframework.kafka.config.ConcurrentKafkaListenerContainerFactory; 11 | import org.springframework.kafka.config.KafkaListenerContainerFactory; 12 | import org.springframework.kafka.core.ConsumerFactory; 13 | import org.springframework.kafka.core.DefaultKafkaConsumerFactory; 14 | import org.springframework.kafka.listener.ConcurrentMessageListenerContainer; 15 | 16 | import java.util.HashMap; 17 | import java.util.Map; 18 | 19 | @Configuration 20 | @EnableKafka 21 | public class KafkaConsumerConfig { 22 | 23 | @Value("${kafka.bootstrap-servers}") 24 | private String bootstrapServers; 25 | 26 | @Bean 27 | public Map consumerConfigs() { 28 | Map props = new HashMap<>(); 29 | // list of host:port pairs used for establishing the initial connections to the Kafka cluster 30 | props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers); 31 | props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class); 32 | props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class); 33 | // allows a pool of processes to divide the work of consuming and processing records 34 | props.put(ConsumerConfig.GROUP_ID_CONFIG, "testTopicGroup"); 35 | // automatically reset the offset to the earliest offset 36 | props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest"); 37 | 38 | return props; 39 | } 40 | 41 | @Bean 42 | public ConsumerFactory consumerFactory() { 43 | return new DefaultKafkaConsumerFactory<>(consumerConfigs()); 44 | } 45 | 46 | @Bean 47 | @Primary 48 | public KafkaListenerContainerFactory> kafkaListenerContainerFactory() { 49 | ConcurrentKafkaListenerContainerFactory factory = new ConcurrentKafkaListenerContainerFactory<>(); 50 | factory.setConsumerFactory(consumerFactory()); 51 | 52 | return factory; 53 | } 54 | 55 | @Bean(name = "kafkaListenerContainerFactoryWith6Consumer") 56 | public KafkaListenerContainerFactory> kafkaListenerContainerFactoryWith6Consumer() { 57 | ConcurrentKafkaListenerContainerFactory factory = new ConcurrentKafkaListenerContainerFactory<>(); 58 | factory.setConcurrency(6); //3 partition -> 6 thread in parallel in a single consumer 59 | factory.setConsumerFactory(consumerFactory()); 60 | return factory; 61 | } 62 | 63 | @Bean(name = "kafkaListenerContainerFactoryForBatchConsumer") 64 | public KafkaListenerContainerFactory> kafkaListenerContainerFactoryForBatchConsumer() { 65 | ConcurrentKafkaListenerContainerFactory factory = new ConcurrentKafkaListenerContainerFactory<>(); 66 | factory.setConcurrency(1); 67 | factory.setBatchListener(true); 68 | factory.setConsumerFactory(consumerFactory()); 69 | return factory; 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /src/main/java/com/ay/testlab/kafka/KafkaProducerConfig.java: -------------------------------------------------------------------------------- 1 | package com.ay.testlab.kafka; 2 | 3 | import org.apache.kafka.clients.producer.ProducerConfig; 4 | import org.apache.kafka.common.serialization.StringSerializer; 5 | import org.springframework.beans.factory.annotation.Value; 6 | import org.springframework.context.annotation.Bean; 7 | import org.springframework.context.annotation.Configuration; 8 | import org.springframework.kafka.annotation.EnableKafka; 9 | import org.springframework.kafka.core.DefaultKafkaProducerFactory; 10 | import org.springframework.kafka.core.KafkaTemplate; 11 | import org.springframework.kafka.core.ProducerFactory; 12 | 13 | import java.util.HashMap; 14 | import java.util.Map; 15 | 16 | @Configuration 17 | public class KafkaProducerConfig { 18 | 19 | @Value("${kafka.bootstrap-servers}") 20 | private String bootstrapServers; 21 | 22 | @Bean 23 | public Map producerConfigs() { 24 | Map props = new HashMap<>(); 25 | // list of host:port pairs used for establishing the initial connections to the Kakfa cluster 26 | props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers); 27 | props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class); 28 | props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class); 29 | 30 | return props; 31 | } 32 | 33 | @Bean 34 | public ProducerFactory producerFactory() { 35 | return new DefaultKafkaProducerFactory<>(producerConfigs()); 36 | } 37 | 38 | @Bean 39 | public KafkaTemplate kafkaTemplate() { 40 | return new KafkaTemplate<>(producerFactory()); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/com/ay/testlab/kafka/batchlistener/BatchMessageConsumer.java: -------------------------------------------------------------------------------- 1 | package com.ay.testlab.kafka.batchlistener; 2 | 3 | import org.slf4j.Logger; 4 | import org.slf4j.LoggerFactory; 5 | import org.springframework.kafka.annotation.KafkaListener; 6 | import org.springframework.kafka.support.KafkaHeaders; 7 | import org.springframework.messaging.handler.annotation.Header; 8 | import org.springframework.messaging.handler.annotation.Payload; 9 | 10 | import java.util.List; 11 | 12 | public class BatchMessageConsumer { 13 | 14 | private static final Logger LOGGER = LoggerFactory.getLogger(BatchMessageConsumer.class); 15 | 16 | private int consumerTriggerCount = 0; 17 | 18 | @KafkaListener(topics = "${kafka.topic.batchConsumerTopic}", containerFactory = "kafkaListenerContainerFactoryForBatchConsumer", groupId = "batchConsumer") 19 | public void receive(@Payload List payloads, 20 | @Header(KafkaHeaders.RECEIVED_PARTITION_ID) List partitionIds, 21 | @Header(KafkaHeaders.OFFSET) List offsets) { 22 | LOGGER.info("Received group=batchConsumer with batch group data: "); 23 | consumerTriggerCount++; 24 | for (int i = 0; i< payloads.size(); ++i) { 25 | LOGGER.info("---------------- consumerTriggerCount='{}' payload='{}' from partitionId@offset='{}'", consumerTriggerCount, payloads.get(i), partitionIds.get(i)+"@"+offsets.get(i)); 26 | } 27 | 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/com/ay/testlab/kafka/batchlistener/BatchMessageConsumingExample.java: -------------------------------------------------------------------------------- 1 | package com.ay.testlab.kafka.batchlistener; 2 | 3 | import org.slf4j.Logger; 4 | import org.slf4j.LoggerFactory; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.beans.factory.annotation.Value; 7 | import org.springframework.context.annotation.Bean; 8 | import org.springframework.stereotype.Component; 9 | 10 | @Component 11 | public class BatchMessageConsumingExample { 12 | 13 | private static final Logger LOGGER = LoggerFactory.getLogger(BatchMessageConsumingExample.class); 14 | 15 | @Autowired 16 | private MessageProducerForBatchListener sender; 17 | 18 | @Value("${kafka.topic.batchConsumerTopic}") 19 | private String topicName; 20 | 21 | public void execute() { 22 | LOGGER.info("BatchMessageConsumingExample is executing..."); 23 | for (int j = 0; j < 10 ; j++) { 24 | try { 25 | Thread.sleep(10); //add some lag to producer 26 | for (int i = 0; i < 100; ++i) { 27 | sender.send(topicName, "BatchMessageConsuming - Message No = " + i); 28 | } 29 | } catch (InterruptedException e) { 30 | e.printStackTrace(); 31 | } 32 | } 33 | } 34 | 35 | @Bean 36 | public MessageProducerForBatchListener messageProducer(){ 37 | return new MessageProducerForBatchListener(); 38 | } 39 | 40 | @Bean 41 | public BatchMessageConsumer batchMessageConsumer(){ 42 | return new BatchMessageConsumer(); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/main/java/com/ay/testlab/kafka/batchlistener/MessageProducerForBatchListener.java: -------------------------------------------------------------------------------- 1 | package com.ay.testlab.kafka.batchlistener; 2 | 3 | import org.slf4j.Logger; 4 | import org.slf4j.LoggerFactory; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.kafka.core.KafkaTemplate; 7 | 8 | public class MessageProducerForBatchListener { 9 | 10 | private static final Logger LOGGER = LoggerFactory.getLogger(MessageProducerForBatchListener.class); 11 | 12 | @Autowired 13 | private KafkaTemplate kafkaTemplate; 14 | 15 | public void send(String topic, String payload){ 16 | LOGGER.info("Sending payload='{}' to topic='{}' with key='{}'", payload, topic); 17 | kafkaTemplate.send(topic, payload); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/com/ay/testlab/kafka/multipartition/MultiPartitionMessageConsumer.java: -------------------------------------------------------------------------------- 1 | package com.ay.testlab.kafka.multipartition; 2 | 3 | import org.slf4j.Logger; 4 | import org.slf4j.LoggerFactory; 5 | import org.springframework.kafka.annotation.KafkaListener; 6 | import org.springframework.kafka.support.KafkaHeaders; 7 | import org.springframework.messaging.handler.annotation.Header; 8 | import org.springframework.messaging.handler.annotation.Payload; 9 | 10 | public class MultiPartitionMessageConsumer { 11 | 12 | private static final Logger LOGGER = LoggerFactory.getLogger(MultiPartitionMessageConsumer.class); 13 | 14 | @KafkaListener(topics = "${kafka.topic.multiPartitionTopic}", groupId = "multiPartitionWith2Consumer") 15 | public void receiver1a(@Payload String payload, 16 | @Header(KafkaHeaders.RECEIVED_PARTITION_ID)Long partitionId, 17 | @Header(KafkaHeaders.OFFSET)Long offset) { 18 | LOGGER.info("Received consumer=1a group=multiPartitionWith2Consumer payload='{}' from partitionId@offset='{}'", payload, partitionId+"@"+offset); 19 | } 20 | 21 | @KafkaListener(topics = "${kafka.topic.multiPartitionTopic}", groupId = "multiPartitionWith2Consumer") 22 | public void receiver1b(@Payload String payload, 23 | @Header(KafkaHeaders.RECEIVED_PARTITION_ID)Long partitionId, 24 | @Header(KafkaHeaders.OFFSET)Long offset) { 25 | LOGGER.info("Received consumer=1b group=multiPartitionWith2Consumer payload='{}' from partitionId@offset='{}'", payload, partitionId+"@"+offset); 26 | } 27 | 28 | @KafkaListener(topics = "${kafka.topic.multiPartitionTopic}", containerFactory = "kafkaListenerContainerFactoryWith6Consumer", groupId = "multiPartitionWithSingleConsumer6Thread") 29 | public void receiver2(@Payload String payload, 30 | @Header(KafkaHeaders.RECEIVED_PARTITION_ID)Long partitionId, 31 | @Header(KafkaHeaders.OFFSET)Long offset) { 32 | LOGGER.info("Received consumer=2 group=multiPartitionWithSingleConsumer6Thread payload='{}' from partitionId@offset='{}'", payload, partitionId+"@"+offset); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/com/ay/testlab/kafka/multipartition/MultiPartitionMessageProducer.java: -------------------------------------------------------------------------------- 1 | package com.ay.testlab.kafka.multipartition; 2 | 3 | import org.slf4j.Logger; 4 | import org.slf4j.LoggerFactory; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.kafka.core.KafkaTemplate; 7 | import org.springframework.kafka.support.SendResult; 8 | import org.springframework.util.concurrent.FailureCallback; 9 | import org.springframework.util.concurrent.ListenableFuture; 10 | import org.springframework.util.concurrent.SuccessCallback; 11 | 12 | public class MultiPartitionMessageProducer { 13 | 14 | private static final Logger LOGGER = LoggerFactory.getLogger(MultiPartitionMessageProducer.class); 15 | 16 | @Autowired 17 | private KafkaTemplate kafkaTemplate; 18 | 19 | public void send(String topic, String key, String payload){ 20 | LOGGER.info("Sending payload='{}' to topic='{}' with key='{}'", payload, topic, key); 21 | ListenableFuture> future = kafkaTemplate.send(topic, key ,payload); 22 | SuccessCallback> successCallback = sendResult -> { 23 | LOGGER.info("Sent payload='{}' with key='{}' to topic-partition@offset='{}'", payload, key, sendResult.getRecordMetadata().toString()); 24 | }; 25 | FailureCallback failureCallback = throwable -> { 26 | LOGGER.info("Sending payload='{}' to topic='{}' with key='{}' failed!!!", payload, topic, key); 27 | }; 28 | future.addCallback(successCallback, failureCallback); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/com/ay/testlab/kafka/multipartition/MultiPartitionMessagingExample.java: -------------------------------------------------------------------------------- 1 | package com.ay.testlab.kafka.multipartition; 2 | 3 | import org.slf4j.Logger; 4 | import org.slf4j.LoggerFactory; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.beans.factory.annotation.Value; 7 | import org.springframework.context.annotation.Bean; 8 | import org.springframework.stereotype.Component; 9 | 10 | /** 11 | * MultiPartitionMessaging uses Spring Boot CommandLineRunner to send 300 consecutive messages to 10 partition of Kafka server 12 | */ 13 | @Component 14 | public class MultiPartitionMessagingExample { 15 | 16 | private static final Logger LOGGER = LoggerFactory.getLogger(MultiPartitionMessagingExample.class); 17 | 18 | @Autowired 19 | private MultiPartitionMessageProducer sender; 20 | 21 | @Value("${kafka.topic.multiPartitionTopic}") 22 | private String topicName; 23 | 24 | public void execute() { 25 | LOGGER.info("MultiPartitionMessagingExample is executing..."); 26 | for (int i = 0; i < 30; ++i) { 27 | for(int partitionKey = 1; partitionKey<=10; ++ partitionKey) { 28 | sender.send(topicName, "key"+partitionKey, "MultiPartitionMessaging - Message No = " +partitionKey+"-"+i); 29 | } 30 | } 31 | } 32 | 33 | @Bean 34 | public MultiPartitionMessageProducer multiPartitionMessageProducer(){ 35 | return new MultiPartitionMessageProducer(); 36 | } 37 | 38 | @Bean 39 | public MultiPartitionMessageConsumer multiPartitionMessageConsumer(){ 40 | return new MultiPartitionMessageConsumer(); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/com/ay/testlab/kafka/rest/SimpleController.java: -------------------------------------------------------------------------------- 1 | package com.ay.testlab.kafka.rest; 2 | 3 | import org.springframework.web.bind.annotation.RequestMapping; 4 | import org.springframework.web.bind.annotation.RestController; 5 | 6 | @RestController 7 | public class SimpleController { 8 | 9 | @RequestMapping("/Hello") 10 | public String index() { 11 | return "Greetings from Spring Boot!"; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/com/ay/testlab/kafka/simplemessage/SimpleKafkaMessageConsumer.java: -------------------------------------------------------------------------------- 1 | package com.ay.testlab.kafka.simplemessage; 2 | 3 | import org.slf4j.Logger; 4 | import org.slf4j.LoggerFactory; 5 | import org.springframework.kafka.annotation.KafkaListener; 6 | 7 | public class SimpleKafkaMessageConsumer { 8 | 9 | private static final Logger LOGGER = LoggerFactory.getLogger(SimpleKafkaMessageConsumer.class); 10 | 11 | private String message = null; 12 | 13 | @KafkaListener(topics = "${kafka.topic.simpleMessageTopic}") 14 | public void receive(String payload) { 15 | LOGGER.info("Received payload='{}'", payload); 16 | this.message = payload; 17 | } 18 | 19 | //added for testing purpose 20 | public String message(){return this.message;} 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/com/ay/testlab/kafka/simplemessage/SimpleKafkaMessageProducer.java: -------------------------------------------------------------------------------- 1 | package com.ay.testlab.kafka.simplemessage; 2 | 3 | import org.slf4j.Logger; 4 | import org.slf4j.LoggerFactory; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.kafka.core.KafkaTemplate; 7 | 8 | public class SimpleKafkaMessageProducer { 9 | 10 | private static final Logger LOGGER = LoggerFactory.getLogger(SimpleKafkaMessageProducer.class); 11 | 12 | @Autowired 13 | private KafkaTemplate kafkaTemplate; 14 | 15 | public void send(String topic, String payload){ 16 | LOGGER.info("Sending payload='{}' to topic='{}'", payload, topic); 17 | kafkaTemplate.send(topic, payload); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/com/ay/testlab/kafka/simplemessage/SimpleKafkaMessagingExample.java: -------------------------------------------------------------------------------- 1 | package com.ay.testlab.kafka.simplemessage; 2 | 3 | import org.slf4j.Logger; 4 | import org.slf4j.LoggerFactory; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.beans.factory.annotation.Value; 7 | import org.springframework.context.annotation.Bean; 8 | import org.springframework.stereotype.Component; 9 | 10 | /** 11 | * SimpleKafkaMessaging uses Spring Boot CommandLineRunner to send 100 consecutive messages to Kafka server 12 | */ 13 | @Component 14 | public class SimpleKafkaMessagingExample { 15 | 16 | private static final Logger LOGGER = LoggerFactory.getLogger(SimpleKafkaMessagingExample.class); 17 | 18 | @Autowired 19 | private SimpleKafkaMessageProducer sender; 20 | 21 | @Value("${kafka.topic.simpleMessageTopic}") 22 | private String topicName; 23 | 24 | public void execute() { 25 | LOGGER.info("SimpleKafkaMessagingExample is executing..."); 26 | for (int i = 0; i < 100; ++i) { 27 | sender.send(topicName, "SimpleKafkaMessaging - Message No = " + i); 28 | } 29 | } 30 | 31 | @Bean 32 | public SimpleKafkaMessageProducer simpleKafkaMessageProducer(){ 33 | return new SimpleKafkaMessageProducer(); 34 | } 35 | 36 | @Bean 37 | public SimpleKafkaMessageConsumer simpleKafkaMessageConsumer(){ 38 | return new SimpleKafkaMessageConsumer(); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/com/ay/testlab/kafka/streamapi/KafkaStreamExample.java: -------------------------------------------------------------------------------- 1 | package com.ay.testlab.kafka.streamapi; 2 | 3 | import org.slf4j.Logger; 4 | import org.slf4j.LoggerFactory; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.beans.factory.annotation.Value; 7 | import org.springframework.context.annotation.Bean; 8 | import org.springframework.stereotype.Component; 9 | 10 | @Component 11 | public class KafkaStreamExample { 12 | 13 | private static final Logger LOGGER = LoggerFactory.getLogger(KafkaStreamExample.class); 14 | 15 | @Autowired 16 | private SimpleKafkaMessageProducerForStreaming sender; 17 | 18 | @Value("${kafka.topic.streamRawDataTopic}") 19 | private String streamRawDataTopic; 20 | 21 | public void execute() { 22 | LOGGER.info("KafkaStreamExample is executing..."); 23 | for (int i = 0; i < 100; ++i) { 24 | sender.send(streamRawDataTopic, "SimpleKafkaMessaging - Message No = " + i); 25 | } 26 | } 27 | 28 | 29 | @Bean 30 | public SimpleKafkaMessageProducerForStreaming simpleKafkaMessageProducerForStreaming(){ 31 | return new SimpleKafkaMessageProducerForStreaming(); 32 | } 33 | 34 | @Bean 35 | public SimpleKafkaMessageConsumerForStreaming simpleKafkaMessageConsumerForStreaming(){ return new SimpleKafkaMessageConsumerForStreaming(); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/com/ay/testlab/kafka/streamapi/SimpleKafkaMessageConsumerForStreaming.java: -------------------------------------------------------------------------------- 1 | package com.ay.testlab.kafka.streamapi; 2 | 3 | import org.slf4j.Logger; 4 | import org.slf4j.LoggerFactory; 5 | import org.springframework.kafka.annotation.KafkaListener; 6 | 7 | public class SimpleKafkaMessageConsumerForStreaming { 8 | 9 | private static final Logger LOGGER = LoggerFactory.getLogger(SimpleKafkaMessageConsumerForStreaming.class); 10 | 11 | @KafkaListener(topics = "${kafka.topic.streamProcessedDataTopic}") 12 | public void receive(String payload) { 13 | LOGGER.info("Received payload='{}'", payload); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/com/ay/testlab/kafka/streamapi/SimpleKafkaMessageProducerForStreaming.java: -------------------------------------------------------------------------------- 1 | package com.ay.testlab.kafka.streamapi; 2 | 3 | import org.slf4j.Logger; 4 | import org.slf4j.LoggerFactory; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.kafka.core.KafkaTemplate; 7 | 8 | public class SimpleKafkaMessageProducerForStreaming { 9 | 10 | private static final Logger LOGGER = LoggerFactory.getLogger(SimpleKafkaMessageProducerForStreaming.class); 11 | 12 | @Autowired 13 | private KafkaTemplate kafkaTemplate; 14 | 15 | public void send(String topic, String payload){ 16 | LOGGER.info("Sending payload='{}' to topic='{}'", payload, topic); 17 | kafkaTemplate.send(topic, payload); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/com/ay/testlab/kafka/streamapi/SimpleKafkaStream.java: -------------------------------------------------------------------------------- 1 | package com.ay.testlab.kafka.streamapi; 2 | 3 | import org.apache.kafka.common.serialization.Serdes; 4 | import org.apache.kafka.streams.StreamsBuilder; 5 | import org.apache.kafka.streams.StreamsConfig; 6 | import org.apache.kafka.streams.kstream.KStream; 7 | import org.apache.kafka.streams.processor.WallclockTimestampExtractor; 8 | import org.slf4j.Logger; 9 | import org.slf4j.LoggerFactory; 10 | import org.springframework.beans.factory.annotation.Value; 11 | import org.springframework.context.annotation.Bean; 12 | import org.springframework.context.annotation.Configuration; 13 | import org.springframework.kafka.annotation.EnableKafka; 14 | import org.springframework.kafka.annotation.EnableKafkaStreams; 15 | import org.springframework.kafka.annotation.KafkaStreamsDefaultConfiguration; 16 | import org.springframework.kafka.config.KafkaStreamsConfiguration; 17 | import org.springframework.kafka.config.StreamsBuilderFactoryBeanCustomizer; 18 | 19 | import java.util.HashMap; 20 | import java.util.Map; 21 | 22 | @Configuration 23 | @EnableKafka 24 | @EnableKafkaStreams 25 | public class SimpleKafkaStream { 26 | 27 | private static final Logger LOGGER = LoggerFactory.getLogger(SimpleKafkaStream.class); 28 | 29 | @Value("${kafka.bootstrap-servers}") 30 | private String bootstrapServers; 31 | 32 | @Value("${kafka.topic.streamRawDataTopic}") 33 | private String rawDataTopic; 34 | 35 | @Value("${kafka.topic.streamProcessedDataTopic}") 36 | private String processedDataTopic; 37 | 38 | @Bean(name = KafkaStreamsDefaultConfiguration.DEFAULT_STREAMS_CONFIG_BEAN_NAME) 39 | public KafkaStreamsConfiguration kafkaStreamsConfigs() { 40 | Map props = new HashMap<>(); 41 | props.put(StreamsConfig.APPLICATION_ID_CONFIG, "simpleKafkaStream"); 42 | props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers); 43 | props.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass().getName()); 44 | props.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, Serdes.String().getClass().getName()); 45 | props.put(StreamsConfig.DEFAULT_TIMESTAMP_EXTRACTOR_CLASS_CONFIG, WallclockTimestampExtractor.class.getName()); 46 | return new KafkaStreamsConfiguration(props); 47 | } 48 | 49 | @Bean 50 | public StreamsBuilderFactoryBeanCustomizer customizer() { 51 | return fb -> fb.setStateListener((newState, oldState) -> { 52 | LOGGER.info("State transition from " + oldState + " to " + newState); 53 | }); 54 | } 55 | 56 | @Bean 57 | public KStream kafkaStream(StreamsBuilder kStreamBuilder) { 58 | KStream stream = kStreamBuilder.stream(rawDataTopic); 59 | 60 | //process messages (reverse order) 61 | stream.mapValues( messageValue -> { 62 | LOGGER.info("Stream:SimpleKafkaStream processing payloads='{}'", messageValue); 63 | return new StringBuilder(messageValue).reverse().toString(); 64 | }).to(processedDataTopic); 65 | 66 | LOGGER.info("Stream started here..."); 67 | return stream; 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | kafka: 2 | bootstrap-servers: localhost:9092 3 | topic: 4 | simpleMessageTopic: kafkaSimpleMessageTopic 5 | multiPartitionTopic: kafkaMultiPartitionTopic 6 | batchConsumerTopic: kafkaBatchConsumerTopic 7 | streamRawDataTopic: kafkaStreamRawDataTopic 8 | streamProcessedDataTopic: kafkaStreamProcessedDataTopic -------------------------------------------------------------------------------- /src/test/java/com/ay/testlab/kafka/SimpleKafkaMessageTest.java: -------------------------------------------------------------------------------- 1 | package com.ay.testlab.kafka; 2 | 3 | import com.ay.testlab.kafka.simplemessage.SimpleKafkaMessageConsumer; 4 | import com.ay.testlab.kafka.simplemessage.SimpleKafkaMessageProducer; 5 | import org.junit.jupiter.api.Assertions; 6 | import org.junit.jupiter.api.Test; 7 | import org.junit.jupiter.api.extension.ExtendWith; 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | import org.springframework.beans.factory.annotation.Value; 10 | import org.springframework.boot.test.context.SpringBootTest; 11 | import org.springframework.kafka.test.EmbeddedKafkaBroker; 12 | import org.springframework.kafka.test.context.EmbeddedKafka; 13 | import org.springframework.test.annotation.DirtiesContext; 14 | import org.springframework.test.context.ActiveProfiles; 15 | import org.springframework.test.context.junit.jupiter.SpringExtension; 16 | 17 | import java.util.concurrent.TimeUnit; 18 | 19 | @ExtendWith(SpringExtension.class) 20 | @SpringBootTest 21 | @DirtiesContext 22 | @EmbeddedKafka 23 | @ActiveProfiles("test") 24 | public class SimpleKafkaMessageTest { 25 | 26 | @Value("${kafka.topic.simpleMessageTopic}") 27 | private String topicName; 28 | 29 | @Autowired 30 | private SimpleKafkaMessageProducer sender; 31 | 32 | @Autowired 33 | private SimpleKafkaMessageConsumer consumer; 34 | 35 | @Test 36 | public void testSendReceive(EmbeddedKafkaBroker broker) throws Exception { 37 | sender.send(topicName, "test Message"); 38 | TimeUnit.SECONDS.sleep(1); 39 | Assertions.assertEquals("test Message", consumer.message()); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/test/resources/application.yml: -------------------------------------------------------------------------------- 1 | kafka: 2 | bootstrap-servers: ${spring.embedded.kafka.brokers} 3 | topic: 4 | simpleMessageTopic: testingTopic 5 | multiPartitionTopic: dummy 6 | batchConsumerTopic: dummy 7 | streamRawDataTopic: dummy 8 | streamProcessedDataTopic: dummy --------------------------------------------------------------------------------