├── .gitignore ├── src ├── test │ └── java │ │ └── jc │ │ └── DemoApplicationTests.java └── main │ ├── java │ ├── xml │ │ └── DemoApplication.java │ └── jc │ │ └── DemoApplication.java │ └── resources │ └── xml │ └── outbound-kafka-integration.xml ├── pom.xml ├── LICENSE └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | target/ 2 | pom.xml.tag 3 | pom.xml.releaseBackup 4 | pom.xml.versionsBackup 5 | pom.xml.next 6 | release.properties 7 | dependency-reduced-pom.xml 8 | buildNumber.properties 9 | -------------------------------------------------------------------------------- /src/test/java/jc/DemoApplicationTests.java: -------------------------------------------------------------------------------- 1 | package jc; 2 | 3 | import org.junit.Test; 4 | import org.junit.runner.RunWith; 5 | import org.springframework.test.context.web.WebAppConfiguration; 6 | import org.springframework.boot.test.SpringApplicationConfiguration; 7 | import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; 8 | 9 | @RunWith(SpringJUnit4ClassRunner.class) 10 | @SpringApplicationConfiguration(classes = DemoApplication.class) 11 | @WebAppConfiguration 12 | public class DemoApplicationTests { 13 | 14 | @Test 15 | public void contextLoads() { 16 | } 17 | 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/xml/DemoApplication.java: -------------------------------------------------------------------------------- 1 | package xml; 2 | 3 | import org.apache.commons.logging.Log; 4 | import org.apache.commons.logging.LogFactory; 5 | import org.springframework.beans.factory.annotation.Qualifier; 6 | import org.springframework.boot.CommandLineRunner; 7 | import org.springframework.boot.SpringApplication; 8 | import org.springframework.boot.autoconfigure.SpringBootApplication; 9 | import org.springframework.context.annotation.Bean; 10 | import org.springframework.context.annotation.DependsOn; 11 | import org.springframework.context.annotation.ImportResource; 12 | import org.springframework.integration.config.EnableIntegration; 13 | import org.springframework.messaging.MessageChannel; 14 | import org.springframework.messaging.support.GenericMessage; 15 | 16 | @SpringBootApplication 17 | @EnableIntegration 18 | @ImportResource("/xml/outbound-kafka-integration.xml") 19 | public class DemoApplication { 20 | 21 | private Log log = LogFactory.getLog(getClass()); 22 | 23 | @Bean 24 | @DependsOn("kafkaOutboundChannelAdapter") 25 | CommandLineRunner kickOff(@Qualifier("inputToKafka") MessageChannel in) { 26 | return args -> { 27 | for (int i = 0; i < 1000; i++) { 28 | in.send(new GenericMessage<>("#" + i)); 29 | log.info("sending message #" + i); 30 | } 31 | }; 32 | } 33 | 34 | 35 | public static void main(String args[]) { 36 | SpringApplication.run(DemoApplication.class, args); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/main/resources/xml/outbound-kafka-integration.xml: -------------------------------------------------------------------------------- 1 | 2 | 11 | 12 | 13 | 14 | 15 | 16 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 30 | 31 | 32 | 33 | 34 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | org.test 7 | demo 8 | 0.0.1-SNAPSHOT 9 | jar 10 | 11 | 12 | org.springframework.boot 13 | spring-boot-starter-parent 14 | 1.2.3.RELEASE 15 | 16 | 17 | 18 | UTF-8 19 | 1.8 20 | 21 | 22 | 23 | 24 | org.apache.kafka 25 | kafka_2.10 26 | 0.8.1.1 27 | 28 | 29 | org.springframework.boot 30 | spring-boot-starter-integration 31 | 32 | 33 | org.springframework.boot 34 | spring-boot-starter 35 | 36 | 37 | org.springframework.integration 38 | spring-integration-kafka 39 | 1.1.1.RELEASE 40 | 41 | 42 | org.springframework.integration 43 | spring-integration-java-dsl 44 | 1.1.0.M1 45 | 46 | 47 | org.springframework.boot 48 | spring-boot-starter-test 49 | test 50 | 51 | 52 | 53 | 54 | 55 | libs-milestone-local 56 | http://repo.spring.io/simple/libs-milestone-local/ 57 | 58 | 59 | 60 | 61 | 62 | org.springframework.boot 63 | spring-boot-maven-plugin 64 | 65 | 66 | 67 | 68 | 69 | -------------------------------------------------------------------------------- /src/main/java/jc/DemoApplication.java: -------------------------------------------------------------------------------- 1 | package jc; 2 | 3 | import org.apache.commons.logging.Log; 4 | import org.apache.commons.logging.LogFactory; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.beans.factory.annotation.Qualifier; 7 | import org.springframework.beans.factory.annotation.Value; 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.Configuration; 13 | import org.springframework.context.annotation.DependsOn; 14 | import org.springframework.integration.IntegrationMessageHeaderAccessor; 15 | import org.springframework.integration.config.EnableIntegration; 16 | import org.springframework.integration.dsl.IntegrationFlow; 17 | import org.springframework.integration.dsl.IntegrationFlows; 18 | import org.springframework.integration.dsl.SourcePollingChannelAdapterSpec; 19 | import org.springframework.integration.dsl.kafka.Kafka; 20 | import org.springframework.integration.dsl.kafka.KafkaHighLevelConsumerMessageSourceSpec; 21 | import org.springframework.integration.dsl.kafka.KafkaProducerMessageHandlerSpec; 22 | import org.springframework.integration.dsl.support.Consumer; 23 | import org.springframework.integration.kafka.support.ZookeeperConnect; 24 | import org.springframework.messaging.MessageChannel; 25 | import org.springframework.messaging.support.GenericMessage; 26 | import org.springframework.stereotype.Component; 27 | 28 | import java.util.List; 29 | import java.util.Map; 30 | 31 | /** 32 | * Demonstrates using the Spring Integration Apache Kafka Java Configuration DSL. 33 | * Thanks to Spring Integration ninja Artem Bilan 34 | * for getting the Java Configuration DSL working so quickly! 35 | * 36 | * @author Josh Long 37 | */ 38 | @EnableIntegration 39 | @SpringBootApplication 40 | public class DemoApplication { 41 | 42 | public static final String TEST_TOPIC_ID = "event-stream"; 43 | 44 | /** 45 | * common values used in both the consumer and producer configuration classes. 46 | * This is a poor-man's {@link org.springframework.boot.context.properties.ConfigurationProperties}! 47 | */ 48 | @Component 49 | public static class KafkaConfig { 50 | 51 | @Value("${kafka.topic:" + TEST_TOPIC_ID + "}") 52 | private String topic; 53 | 54 | @Value("${kafka.address:localhost:9092}") 55 | private String brokerAddress; 56 | 57 | @Value("${zookeeper.address:localhost:2181}") 58 | private String zookeeperAddress; 59 | 60 | KafkaConfig() { 61 | } 62 | 63 | public KafkaConfig(String t, String b, String zk) { 64 | this.topic = t; 65 | this.brokerAddress = b; 66 | this.zookeeperAddress = zk; 67 | } 68 | 69 | public String getTopic() { 70 | return topic; 71 | } 72 | 73 | public String getBrokerAddress() { 74 | return brokerAddress; 75 | } 76 | 77 | public String getZookeeperAddress() { 78 | return zookeeperAddress; 79 | } 80 | } 81 | 82 | @Configuration 83 | public static class ProducerConfiguration { 84 | 85 | @Autowired 86 | private KafkaConfig kafkaConfig; 87 | 88 | private static final String OUTBOUND_ID = "outbound"; 89 | 90 | private Log log = LogFactory.getLog(getClass()); 91 | 92 | @Bean 93 | @DependsOn(OUTBOUND_ID) 94 | CommandLineRunner kickOff(@Qualifier(OUTBOUND_ID + ".input") MessageChannel in) { 95 | return args -> { 96 | for (int i = 0; i < 1000; i++) { 97 | in.send(new GenericMessage<>("#" + i)); 98 | log.info("sending message #" + i); 99 | } 100 | }; 101 | } 102 | 103 | 104 | @Bean(name = OUTBOUND_ID) 105 | IntegrationFlow producer() { 106 | 107 | log.info("starting producer flow.."); 108 | 109 | return flowDefinition -> { 110 | Consumer producerMetadataSpecConsumer = 111 | (KafkaProducerMessageHandlerSpec.ProducerMetadataSpec metadata) -> 112 | metadata.async(true) 113 | .batchNumMessages(10) 114 | .valueClassType(String.class) 115 | .valueEncoder(String::getBytes); 116 | 117 | KafkaProducerMessageHandlerSpec messageHandlerSpec = 118 | Kafka.outboundChannelAdapter(props -> props.put("queue.buffering.max.ms", "15000")) 119 | .messageKey(m -> m.getHeaders().get(IntegrationMessageHeaderAccessor.SEQUENCE_NUMBER)) 120 | .addProducer(this.kafkaConfig.getTopic(), this.kafkaConfig.getBrokerAddress(), producerMetadataSpecConsumer); 121 | flowDefinition 122 | .handle(messageHandlerSpec); 123 | }; 124 | } 125 | } 126 | 127 | @Configuration 128 | public static class ConsumerConfiguration { 129 | 130 | @Autowired 131 | private KafkaConfig kafkaConfig; 132 | 133 | private Log log = LogFactory.getLog(getClass()); 134 | 135 | @Bean 136 | IntegrationFlow consumer() { 137 | 138 | log.info("starting consumer.."); 139 | 140 | KafkaHighLevelConsumerMessageSourceSpec messageSourceSpec = Kafka.inboundChannelAdapter( 141 | new ZookeeperConnect(this.kafkaConfig.getZookeeperAddress())) 142 | .consumerProperties(props -> 143 | props.put("auto.offset.reset", "smallest") 144 | .put("auto.commit.interval.ms", "100")) 145 | .addConsumer("myGroup", metadata -> metadata.consumerTimeout(100) 146 | .topicStreamMap(m -> m.put(this.kafkaConfig.getTopic(), 1)) 147 | .maxMessages(10) 148 | .valueDecoder(String::new)); 149 | 150 | Consumer endpointConfigurer = e -> e.poller(p -> p.fixedDelay(100)); 151 | 152 | return IntegrationFlows 153 | .from(messageSourceSpec, endpointConfigurer) 154 | .>>handle((payload, headers) -> { 155 | payload.entrySet().forEach(e -> log.info(e.getKey() + '=' + e.getValue())); 156 | return null; 157 | }) 158 | .get(); 159 | } 160 | } 161 | 162 | public static void main(String[] args) { 163 | SpringApplication.run(DemoApplication.class, args); 164 | } 165 | } 166 | -------------------------------------------------------------------------------- /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 | 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Apache Kafka and Spring Integration, Spring XD, and the Lattice Distributed Runtime 2 | 3 | Applications generated more and more data than ever before and a huge part of the challenge - before it can even be analyzed - is accommodating the load in the first place. [Apache's Kafka](http://kafka.apache.org) meets this challenge. It was originally designed by LinkedIn and subsequently open-sourced in 2011. The project aims to provide a unified, high-throughput, low-latency platform for handling real-time data feeds. The design is heavily influenced by transaction logs. It is a messaging system, similar to traditional messaging systems like RabbitMQ, ActiveMQ, MQSeries, but it's ideal for log aggregation, persistent messaging, fast (_hundreds_ of megabytes per second!) reads and writes, and can accommodate numerous clients. Naturally, this makes it _perfect_ for cloud-scale architectures! 4 | 5 | Kafka [powers many large production systems](https://cwiki.apache.org/confluence/display/KAFKA/Powered+By). LinkedIn uses it for activity data and operational metrics to power the LinkedIn news feed, and LinkedIn Today, as well as offline analytics going into Hadoop. Twitter uses it as part of their stream-processing infrastructure. Kafka powers online-to-online and online-to-offline messaging at Foursquare. It is used to integrate Foursquare monitoring and production systems with Hadoop-based offline infrastructures. Square uses Kafka as a bus to move all system events through Square's various data centers. This includes metrics, logs, custom events, and so on. On the consumer side, it outputs into Splunk, Graphite, or Esper-like real-time alerting. Netflix uses it for 300-600BN messages per day. It's also used by Airbnb, Mozilla, Goldman Sachs, Tumblr, Yahoo, PayPal, Coursera, Urban Airship, Hotels.com, and a seemingly endless list of other big-web stars. Clearly, it's earning its keep in some powerful systems! 6 | 7 | ## Installing Apache Kafka 8 | There are many different ways to get Apache Kafka installed. If you're on OSX, and you're using Homebrew, it can be as simple as `brew install kafka`. You can also [download the latest distribution from Apache](http://kafka.apache.org/downloads.html). I downloaded `kafka_2.10-0.8.2.1.tgz`, unzipped it, and then within you'll find there's a distribution of [Apache Zookeeper](https://zookeeper.apache.org/) as well as Kafka, so nothing else is required. I installed Apache Kafka in my `$HOME` directory, under another directory, `bin`, then I created an environment variable, `KAFKA_HOME`, that points to `$HOME/bin/kafka`. 9 | 10 | Start Apache Zookeeper first, specifying where the configuration properties file it requires is: 11 | 12 | ``` 13 | $KAFKA_HOME/bin/zookeeper-server-start.sh $KAFKA_HOME/config/zookeeper.properties 14 | 15 | ``` 16 | 17 | The Apache Kafka distribution comes with default configuration files for both Zookeeper and Kafka, which makes getting started easy. You will in more advanced use cases need to customize these files. 18 | 19 | Then start Apache Kafka. It too requires a configuration file, like this: 20 | 21 | ``` 22 | $KAFKA_HOME/bin/kafka-server-start.sh $KAFKA_HOME/config/server.properties 23 | ``` 24 | 25 | The `server.properties` file contains, among other things, default values for where to connect to Apache Zookeeper (`zookeeper.connect`), how much data should be sent across sockets, how many partitions there are by default, and the broker ID (`broker.id` - which must be unique across a cluster). 26 | 27 | There are other scripts in the same directory that can be used to send and receive dummy data, very handy in establishing that everything's up and running! 28 | 29 | Now that Apache Kafka is up and running, let's look at working with Apache Kafka from our application. 30 | 31 | ## Some High Level Concepts.. 32 | 33 | A Kafka _broker_ cluster consists of one or more servers where each may have one or more broker processes running. Apache Kafka is designed to be highly available; there are no _master_ nodes. All nodes are interchangeable. Data is replicated from one node to another to ensure that it is still available in the event of a failure. 34 | 35 | In Kafka, a _topic_ is a category, similar to a JMS destination or both an AMQP exchange and queue. Topics are partitioned, and the choice of which of a topic's partition a message should be sent to is made by the message producer. Each message in the partition is assigned a unique sequenced ID, its _offset_. More partitions allow greater parallelism for consumption, but this will also result in more files across the brokers. 36 | 37 | 38 | _Producers_ send messages to Apache Kafka broker topics and specify the partition to use for every message they produce. Message production may be synchronous or asynchronous. Producers also specify what sort of replication guarantees they want. 39 | 40 | _Consumers_ listen for messages on topics and process the feed of published messages. As you'd expect if you've used other messaging systems, this is usually (and usefully!) asynchronous. 41 | 42 | Like [Spring XD](http://spring.io/projects/spring-xd) and numerous other distributed system, Apache Kafka uses Apache Zookeeper to coordinate cluster information. Apache Zookeeper provides a shared hierarchical namespace (called _znodes_) that nodes can share to understand cluster topology and availability (yet another reason that [Spring Cloud](https://github.com/spring-cloud/spring-cloud-zookeeper) has forthcoming support for it..). 43 | 44 | Zookeeper is very present in your interactions with Apache Kafka. Apache Kafka has, for example, two different APIs for acting as a consumer. The higher level API is simpler to get started with and it handles all the nuances of handling partitioning and so on. It will need a reference to a Zookeeper instance to keep the coordination state. 45 | 46 | Let's turn now turn to using Apache Kafka with Spring. 47 | 48 | ## Using Apache Kafka with Spring Integration 49 | The recently released [Apache Kafka 1.1 Spring Integration adapter]() is very powerful, and provides inbound adapters for working with both the lower level Apache Kafka API as well as the higher level API. 50 | 51 | The adapter, currently, is XML-configuration first, though work is already underway on a Spring Integration Java configuration DSL for the adapter and milestones are available. We'll look at both here, now. 52 | 53 | To make all these examples work, I added the [libs-milestone-local Maven repository](http://repo.spring.io/simple/libs-milestone-local) and used the following dependencies: 54 | 55 | - org.apache.kafka:kafka_2.10:0.8.1.1 56 | - org.springframework.boot:spring-boot-starter-integration:1.2.3.RELEASE 57 | - org.springframework.boot:spring-boot-starter:1.2.3.RELEASE 58 | - org.springframework.integration:spring-integration-kafka:1.1.1.RELEASE 59 | - org.springframework.integration:spring-integration-java-dsl:1.1.0.M1 60 | 61 | ### Using the Spring Integration Apache Kafka with the Spring Integration XML DSL 62 | 63 | First, let's look at how to use the Spring Integration outbound adapter to send `Message` instances from a Spring Integration flow to an external Apache Kafka instance. The example is fairly straightforward: a Spring Integration `channel` named `inputToKafka` acts as a conduit that forwards `Message` messages to the outbound adapter, `kafkaOutboundChannelAdapter`. The adapter itself can take its configuration from the defaults specified in the `kafka:producer-context` element or it from the adapter-local configuration overrides. There may be one or many configurations in a given `kafka:producer-context` element. 64 | 65 | ```xml 66 | 67 | 76 | 77 | 78 | 79 | 80 | 81 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 95 | 96 | 97 | 98 | 99 | ``` 100 | 101 | Here's the Java code from a Spring Boot application to trigger message sends using the outbound adapter by sending messages into the incoming `inputToKafka` `MessageChannel`. 102 | 103 | ```java 104 | package xml; 105 | 106 | import org.apache.commons.logging.Log; 107 | import org.apache.commons.logging.LogFactory; 108 | import org.springframework.beans.factory.annotation.Qualifier; 109 | import org.springframework.boot.CommandLineRunner; 110 | import org.springframework.boot.SpringApplication; 111 | import org.springframework.boot.autoconfigure.SpringBootApplication; 112 | import org.springframework.context.annotation.Bean; 113 | import org.springframework.context.annotation.DependsOn; 114 | import org.springframework.context.annotation.ImportResource; 115 | import org.springframework.integration.config.EnableIntegration; 116 | import org.springframework.messaging.MessageChannel; 117 | import org.springframework.messaging.support.GenericMessage; 118 | 119 | @SpringBootApplication 120 | @EnableIntegration 121 | @ImportResource("/xml/outbound-kafka-integration.xml") 122 | public class DemoApplication { 123 | 124 | private Log log = LogFactory.getLog(getClass()); 125 | 126 | @Bean 127 | @DependsOn("kafkaOutboundChannelAdapter") 128 | CommandLineRunner kickOff(@Qualifier("inputToKafka") MessageChannel in) { 129 | return args -> { 130 | for (int i = 0; i < 1000; i++) { 131 | in.send(new GenericMessage<>("#" + i)); 132 | log.info("sending message #" + i); 133 | } 134 | }; 135 | } 136 | 137 | public static void main(String args[]) { 138 | SpringApplication.run(DemoApplication.class, args); 139 | } 140 | } 141 | 142 | ``` 143 | 144 | ### Using the New Apache Kafka Spring Integration Java Configuration DSL 145 | 146 | Shortly after the Spring Integration 1.1 release, Spring Integration rockstar [Artem Bilan](https://spring.io/team/artembilan) got to work [on adding a Spring Integration Java Configuration DSL analog](http://repo.spring.io/simple/libs-milestone-local/org/springframework/integration/spring-integration-java-dsl/1.1.0.M1/) and the result is a thing of beauty! It's not yet GA (you need to add the `libs-milestone` repository for now), but I encourage you to try it out and kick the tires. It's working well for me and the Spring Integration team are always keen on getting early feedback whenever possible! Here's an example that demonstrates both sending messages and consuming them from two different `IntegrationFlow`s. The producer is similar to the example XML above. 147 | 148 | New in this example is the polling consumer. It is batch-centric, and will pull down all the messages it sees at a fixed interval. In our code, the message received will be a map that contains as its keys the topic and as its value another map with the partition ID and the batch (in this case, of 10 records), of records read. There is a `MessageListenerContainer`-based alternative that processes messages as they come. 149 | 150 | ```java 151 | package jc; 152 | 153 | import org.apache.commons.logging.Log; 154 | import org.apache.commons.logging.LogFactory; 155 | import org.springframework.beans.factory.annotation.Autowired; 156 | import org.springframework.beans.factory.annotation.Qualifier; 157 | import org.springframework.beans.factory.annotation.Value; 158 | import org.springframework.boot.CommandLineRunner; 159 | import org.springframework.boot.SpringApplication; 160 | import org.springframework.boot.autoconfigure.SpringBootApplication; 161 | import org.springframework.context.annotation.Bean; 162 | import org.springframework.context.annotation.Configuration; 163 | import org.springframework.context.annotation.DependsOn; 164 | import org.springframework.integration.IntegrationMessageHeaderAccessor; 165 | import org.springframework.integration.config.EnableIntegration; 166 | import org.springframework.integration.dsl.IntegrationFlow; 167 | import org.springframework.integration.dsl.IntegrationFlows; 168 | import org.springframework.integration.dsl.SourcePollingChannelAdapterSpec; 169 | import org.springframework.integration.dsl.kafka.Kafka; 170 | import org.springframework.integration.dsl.kafka.KafkaHighLevelConsumerMessageSourceSpec; 171 | import org.springframework.integration.dsl.kafka.KafkaProducerMessageHandlerSpec; 172 | import org.springframework.integration.dsl.support.Consumer; 173 | import org.springframework.integration.kafka.support.ZookeeperConnect; 174 | import org.springframework.messaging.MessageChannel; 175 | import org.springframework.messaging.support.GenericMessage; 176 | import org.springframework.stereotype.Component; 177 | 178 | import java.util.List; 179 | import java.util.Map; 180 | 181 | /** 182 | * Demonstrates using the Spring Integration Apache Kafka Java Configuration DSL. 183 | * Thanks to Spring Integration ninja Artem Bilan 184 | * for getting the Java Configuration DSL working so quickly! 185 | * 186 | * @author Josh Long 187 | */ 188 | @EnableIntegration 189 | @SpringBootApplication 190 | public class DemoApplication { 191 | 192 | public static final String TEST_TOPIC_ID = "event-stream"; 193 | 194 | @Component 195 | public static class KafkaConfig { 196 | 197 | @Value("${kafka.topic:" + TEST_TOPIC_ID + "}") 198 | private String topic; 199 | 200 | @Value("${kafka.address:localhost:9092}") 201 | private String brokerAddress; 202 | 203 | @Value("${zookeeper.address:localhost:2181}") 204 | private String zookeeperAddress; 205 | 206 | KafkaConfig() { 207 | } 208 | 209 | public KafkaConfig(String t, String b, String zk) { 210 | this.topic = t; 211 | this.brokerAddress = b; 212 | this.zookeeperAddress = zk; 213 | } 214 | 215 | public String getTopic() { 216 | return topic; 217 | } 218 | 219 | public String getBrokerAddress() { 220 | return brokerAddress; 221 | } 222 | 223 | public String getZookeeperAddress() { 224 | return zookeeperAddress; 225 | } 226 | } 227 | 228 | @Configuration 229 | public static class ProducerConfiguration { 230 | 231 | @Autowired 232 | private KafkaConfig kafkaConfig; 233 | 234 | private static final String OUTBOUND_ID = "outbound"; 235 | 236 | private Log log = LogFactory.getLog(getClass()); 237 | 238 | @Bean 239 | @DependsOn(OUTBOUND_ID) 240 | CommandLineRunner kickOff( 241 | @Qualifier(OUTBOUND_ID + ".input") MessageChannel in) { 242 | return args -> { 243 | for (int i = 0; i < 1000; i++) { 244 | in.send(new GenericMessage<>("#" + i)); 245 | log.info("sending message #" + i); 246 | } 247 | }; 248 | } 249 | 250 | @Bean(name = OUTBOUND_ID) 251 | IntegrationFlow producer() { 252 | 253 | log.info("starting producer flow.."); 254 | return flowDefinition -> { 255 | 256 | Consumer spec = 257 | (KafkaProducerMessageHandlerSpec.ProducerMetadataSpec metadata)-> 258 | metadata.async(true) 259 | .batchNumMessages(10) 260 | .valueClassType(String.class) 261 | .valueEncoder(String::getBytes); 262 | 263 | KafkaProducerMessageHandlerSpec messageHandlerSpec = 264 | Kafka.outboundChannelAdapter( 265 | props -> props.put("queue.buffering.max.ms", "15000")) 266 | .messageKey(m -> m.getHeaders().get(IntegrationMessageHeaderAccessor.SEQUENCE_NUMBER)) 267 | .addProducer(this.kafkaConfig.getTopic(), 268 | this.kafkaConfig.getBrokerAddress(), spec); 269 | flowDefinition 270 | .handle(messageHandlerSpec); 271 | }; 272 | } 273 | } 274 | 275 | @Configuration 276 | public static class ConsumerConfiguration { 277 | 278 | @Autowired 279 | private KafkaConfig kafkaConfig; 280 | 281 | private Log log = LogFactory.getLog(getClass()); 282 | 283 | @Bean 284 | IntegrationFlow consumer() { 285 | 286 | log.info("starting consumer.."); 287 | 288 | KafkaHighLevelConsumerMessageSourceSpec messageSourceSpec = Kafka.inboundChannelAdapter( 289 | new ZookeeperConnect(this.kafkaConfig.getZookeeperAddress())) 290 | .consumerProperties(props -> 291 | props.put("auto.offset.reset", "smallest") 292 | .put("auto.commit.interval.ms", "100")) 293 | .addConsumer("myGroup", metadata -> metadata.consumerTimeout(100) 294 | .topicStreamMap(m -> m.put(this.kafkaConfig.getTopic(), 1)) 295 | .maxMessages(10) 296 | .valueDecoder(String::new)); 297 | 298 | Consumer endpointConfigurer = e -> e.poller(p -> p.fixedDelay(100)); 299 | 300 | return IntegrationFlows 301 | .from(messageSourceSpec, endpointConfigurer) 302 | .>>handle((payload, headers) -> { 303 | payload.entrySet().forEach(e -> log.info(e.getKey() + '=' + e.getValue())); 304 | return null; 305 | }) 306 | .get(); 307 | } 308 | } 309 | 310 | public static void main(String[] args) { 311 | SpringApplication.run(DemoApplication.class, args); 312 | } 313 | } 314 | 315 | ``` 316 | 317 | The example makes heavy use of Java 8 lambdas. 318 | 319 | The producer spends a bit of time establishing how many messages will be sent in a single send operation, how keys and values are encoded (Kafka only knows about `byte[]` arrays, after all) and whether messages should be sent synchronously or asynchronously. In the next line, we configure the outbound adapter itself and then define an `IntegrationFlow` such that all messages get sent out via the Kafka outbound adapter. 320 | 321 | The consumer spends a bit of time establishing which Zookeeper instance to connect to, how many messages to receive (10) in a batch, etc. Once the message batches are recieved, they're handed to the `handle` method where I've passed in a lambda that'll enumerate the payload's body and print it out. Nothing fancy. 322 | 323 | ## Using Apache Kafka with Spring XD 324 | 325 | Apache Kafka is a message bus and it can be very powerful when used as an integration bus. However, it really comes into its own because it's fast enough and scalable enough that it can be used to route big-data through processing pipelines. And if you're doing data processing, you really want [Spring XD](http://projects.spring.io/spring-xd/)! Spring XD makes it dead simple to use Apache Kafka (as the support is built on the Apache Kafka Spring Integration adapter!) in complex stream-processing pipelines. Apache Kafka is exposed as a Spring XD _source_ - where data comes from - and a sink - where data goes to. 326 | 327 | 328 | 329 | Spring XD exposes a super convenient DSL for creating `bash`-like pipes-and-filter flows. Spring XD is a centralized runtime that manages, scales, and monitors data processing jobs. It builds on top of Spring Integration, Spring Batch, Spring Data and Spring for Hadoop to be a one-stop data-processing shop. Spring XD Jobs read data from _sources_, run them through processing components that may count, filter, enrich or transform the data, and then write them to sinks. 330 | 331 | Spring Integration and Spring XD ninja [Marius Bogoevici](https://twitter.com/mariusbogoevici), who did a lot of the recent work in the Spring Integration and Spring XD implementation of Apache Kafka, put together a really nice example demonstrating [how to get a full working Spring XD and Kafka flow working](https://github.com/spring-projects/spring-xd-samples/tree/master/kafka-source). The `README` walks you through getting Apache Kafka, Spring XD and the requisite topics all setup. The essence, however, is when you use the Spring XD shell and the shell DSL to compose a stream. Spring XD components are named components that are pre-configured but have lots of parameters that you can override with `--..` arguments via the XD shell and DSL. (That DSL, by the way, is written by the amazing [Andy Clement](https://spring.io/team/aclement) of Spring Expression language fame!) Here's an example that configures a stream to read data from an Apache Kafka source and then write the message a component called `log`, which is a sink. `log`, in this case, could be syslogd, Splunk, HDFS, etc. 332 | 333 | 334 | 335 | ```bash 336 | xd> stream create kafka-source-test --definition "kafka --zkconnect=localhost:2181 --topic=event-stream | log" --deploy 337 | 338 | ``` 339 | 340 | And that's it! Naturally, this is just a tase of Spring XD, but hopefully you'll agree the possibilities are tantalizing. 341 | 342 | ## Deploying a Kafka Server with Lattice and Docker 343 | It's easy to get an example Kafka installation all setup using [Lattice](http://lattice.cf), a distributed runtime that supports, among other container formats, the very popular Docker image format. [There's a Docker image provided by Spotify that sets up a collocated Zookeeper and Kafka image](https://github.com/spotify/docker-kafka). You can easily deploy this to a Lattice cluster, as follows: 344 | 345 | ```bash 346 | ltc create --run-as-root m-kafka spotify/kafka 347 | ``` 348 | From there, you can easily scale the Apache Kafka instances and even more easily still consume Apache Kafka from your cloud-based services. 349 | 350 | ## Next Steps 351 | 352 | You can find the code [for this blog on my GitHub account](https://github.com/joshlong/spring-and-kafka). 353 | 354 | We've only scratched the surface! 355 | 356 | If you want to learn more (and why wouldn't you?), then be sure to check out Marius Bogoevici and Dr. Mark Pollack's upcoming [webinar on Reactive data-pipelines using Spring XD and Apache Kafka](https://spring.io/blog/2015/03/17/webinar-reactive-data-pipelines-with-spring-xd-and-kafka) where they'll demonstrate how easy it can be to use RxJava, Spring XD and Apache Kafka! 357 | --------------------------------------------------------------------------------