You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@camel.apache.org by da...@apache.org on 2017/10/25 19:17:26 UTC

[camel] branch master updated: CAMEL-11943: camel-kafka supports dynamic topics via pattern.

This is an automated email from the ASF dual-hosted git repository.

davsclaus pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/camel.git


The following commit(s) were added to refs/heads/master by this push:
     new 1fb79d3  CAMEL-11943: camel-kafka supports dynamic topics via pattern.
1fb79d3 is described below

commit 1fb79d33bdcc74103824ae1d1c32c69d889ba07c
Author: Claus Ibsen <cl...@gmail.com>
AuthorDate: Wed Oct 25 21:17:10 2017 +0200

    CAMEL-11943: camel-kafka supports dynamic topics via pattern.
---
 .../camel-kafka/src/main/docs/kafka-component.adoc |  3 +-
 .../camel/component/kafka/KafkaConfiguration.java  | 14 ++++
 .../camel/component/kafka/KafkaConsumer.java       | 60 ++++++++++++--
 .../kafka/KafkaConsumerTopicIsPatternTest.java     | 93 ++++++++++++++++++++++
 .../springboot/KafkaComponentConfiguration.java    | 13 +++
 5 files changed, 177 insertions(+), 6 deletions(-)

diff --git a/components/camel-kafka/src/main/docs/kafka-component.adoc b/components/camel-kafka/src/main/docs/kafka-component.adoc
index 866bd8f..c25589b 100644
--- a/components/camel-kafka/src/main/docs/kafka-component.adoc
+++ b/components/camel-kafka/src/main/docs/kafka-component.adoc
@@ -69,7 +69,7 @@ with the following path and query parameters:
 | *topic* | *Required* Name of the topic to use. On the consumer you can use comma to separate multiple topics. A producer can only send a message to a single topic. |  | String
 |===
 
-==== Query Parameters (87 parameters):
+==== Query Parameters (88 parameters):
 
 [width="100%",cols="2,5,^1,2",options="header"]
 |===
@@ -100,6 +100,7 @@ with the following path and query parameters:
 | *pollTimeoutMs* (consumer) | The timeout used when polling the KafkaConsumer. | 5000 | Long
 | *seekTo* (consumer) | Set if KafkaConsumer will read from beginning or end on startup: beginning : read from beginning end : read from end This is replacing the earlier property seekToBeginning |  | String
 | *sessionTimeoutMs* (consumer) | The timeout used to detect failures when using Kafka's group management facilities. | 10000 | Integer
+| *topicIsPattern* (consumer) | Whether the topic is a pattern (regular expression). This can be used to subscribe to dynamic number of topics matching the pattern. | false | boolean
 | *valueDeserializer* (consumer) | Deserializer class for value that implements the Deserializer interface. | org.apache.kafka.common.serialization.StringDeserializer | String
 | *exceptionHandler* (consumer) | To let the consumer use a custom ExceptionHandler. Notice if the option bridgeErrorHandler is enabled then this options is not in use. By default the consumer will deal with exceptions that will be logged at WARN or ERROR level and ignored. |  | ExceptionHandler
 | *exchangePattern* (consumer) | Sets the exchange pattern when the consumer creates an exchange. |  | ExchangePattern
diff --git a/components/camel-kafka/src/main/java/org/apache/camel/component/kafka/KafkaConfiguration.java b/components/camel-kafka/src/main/java/org/apache/camel/component/kafka/KafkaConfiguration.java
index edb0e18..efa51c3 100644
--- a/components/camel-kafka/src/main/java/org/apache/camel/component/kafka/KafkaConfiguration.java
+++ b/components/camel-kafka/src/main/java/org/apache/camel/component/kafka/KafkaConfiguration.java
@@ -54,6 +54,8 @@ public class KafkaConfiguration implements Cloneable {
     private String clientId;
 
     @UriParam(label = "consumer")
+    private boolean topicIsPattern;
+    @UriParam(label = "consumer")
     private String groupId;
     @UriParam(label = "consumer", defaultValue = "10")
     private int consumerStreams = 10;
@@ -495,6 +497,18 @@ public class KafkaConfiguration implements Cloneable {
         }
     }
 
+    public boolean isTopicIsPattern() {
+        return topicIsPattern;
+    }
+
+    /**
+     * Whether the topic is a pattern (regular expression).
+     * This can be used to subscribe to dynamic number of topics matching the pattern.
+     */
+    public void setTopicIsPattern(boolean topicIsPattern) {
+        this.topicIsPattern = topicIsPattern;
+    }
+
     public String getGroupId() {
         return groupId;
     }
diff --git a/components/camel-kafka/src/main/java/org/apache/camel/component/kafka/KafkaConsumer.java b/components/camel-kafka/src/main/java/org/apache/camel/component/kafka/KafkaConsumer.java
index 0fca9e7..63c9da3 100644
--- a/components/camel-kafka/src/main/java/org/apache/camel/component/kafka/KafkaConsumer.java
+++ b/components/camel-kafka/src/main/java/org/apache/camel/component/kafka/KafkaConsumer.java
@@ -18,6 +18,7 @@ package org.apache.camel.component.kafka;
 
 import java.util.ArrayList;
 import java.util.Arrays;
+import java.util.Collection;
 import java.util.Collections;
 import java.util.Iterator;
 import java.util.List;
@@ -25,6 +26,7 @@ import java.util.Properties;
 import java.util.Set;
 import java.util.UUID;
 import java.util.concurrent.ExecutorService;
+import java.util.regex.Pattern;
 
 import org.apache.camel.Exchange;
 import org.apache.camel.Processor;
@@ -33,6 +35,7 @@ import org.apache.camel.spi.StateRepository;
 import org.apache.camel.util.IOHelper;
 import org.apache.camel.util.ObjectHelper;
 import org.apache.kafka.clients.consumer.ConsumerConfig;
+import org.apache.kafka.clients.consumer.ConsumerRebalanceListener;
 import org.apache.kafka.clients.consumer.ConsumerRecord;
 import org.apache.kafka.clients.consumer.ConsumerRecords;
 import org.apache.kafka.clients.consumer.OffsetAndMetadata;
@@ -95,8 +98,15 @@ public class KafkaConsumer extends DefaultConsumer {
         super.doStart();
 
         executor = endpoint.createExecutor();
+
+        String topic = endpoint.getConfiguration().getTopic();
+        Pattern pattern = null;
+        if (endpoint.getConfiguration().isTopicIsPattern()) {
+            pattern = Pattern.compile(topic);
+        }
+
         for (int i = 0; i < endpoint.getConfiguration().getConsumersCount(); i++) {
-            KafkaFetchRecords task = new KafkaFetchRecords(endpoint.getConfiguration().getTopic(), i + "", getProps());
+            KafkaFetchRecords task = new KafkaFetchRecords(topic, pattern, i + "", getProps());
             executor.submit(task);
             tasks.add(task);
         }
@@ -123,15 +133,17 @@ public class KafkaConsumer extends DefaultConsumer {
         super.doStop();
     }
 
-    class KafkaFetchRecords implements Runnable {
+    class KafkaFetchRecords implements Runnable, ConsumerRebalanceListener {
 
         private org.apache.kafka.clients.consumer.KafkaConsumer consumer;
         private final String topicName;
+        private final Pattern topicPattern;
         private final String threadId;
         private final Properties kafkaProps;
 
-        KafkaFetchRecords(String topicName, String id, Properties kafkaProps) {
+        KafkaFetchRecords(String topicName, Pattern topicPattern, String id, Properties kafkaProps) {
             this.topicName = topicName;
+            this.topicPattern = topicPattern;
             this.threadId = topicName + "-" + "Thread " + id;
             this.kafkaProps = kafkaProps;
         }
@@ -177,8 +189,13 @@ public class KafkaConsumer extends DefaultConsumer {
             boolean reConnect = false;
 
             try {
-                log.info("Subscribing {} to topic {}", threadId, topicName);
-                consumer.subscribe(Arrays.asList(topicName.split(",")));
+                if (topicPattern != null) {
+                    log.info("Subscribing {} to topic pattern {}", threadId, topicName);
+                    consumer.subscribe(topicPattern, this);
+                } else {
+                    log.info("Subscribing {} to topic {}", threadId, topicName);
+                    consumer.subscribe(Arrays.asList(topicName.split(",")));
+                }
 
                 StateRepository<String, String> offsetRepository = endpoint.getConfiguration().getOffsetRepository();
                 if (offsetRepository != null) {
@@ -322,6 +339,7 @@ public class KafkaConsumer extends DefaultConsumer {
         private void commitOffset(StateRepository<String, String> offsetRepository, TopicPartition partition, long partitionLastOffset, boolean forceCommit) {
             if (partitionLastOffset != -1) {
                 if (offsetRepository != null) {
+                    log.debug("Saving offset repository state {} from topic {} with offset: {}", threadId, topicName, partitionLastOffset);
                     offsetRepository.setState(serializeOffsetKey(partition), serializeOffsetValue(partitionLastOffset));
                 } else if (forceCommit) {
                     log.debug("Forcing commitSync {} from topic {} with offset: {}", threadId, topicName, partitionLastOffset);
@@ -337,6 +355,38 @@ public class KafkaConsumer extends DefaultConsumer {
             // As advised in the KAFKA-1894 ticket, calling this wakeup method breaks the infinite loop
             consumer.wakeup();
         }
+
+        @Override
+        public void onPartitionsRevoked(Collection<TopicPartition> partitions) {
+            log.debug("onPartitionsRevoked: {} from topic {}", threadId, topicName);
+
+            StateRepository<String, String> offsetRepository = endpoint.getConfiguration().getOffsetRepository();
+            if (offsetRepository != null) {
+                for (TopicPartition partition : partitions) {
+                    long offset = consumer.position(partition);
+                    log.debug("Saving offset repository state {} from topic {} with offset: {}", threadId, topicName, offset);
+                    offsetRepository.setState(serializeOffsetKey(partition), serializeOffsetValue(offset));
+                }
+            }
+        }
+
+        @Override
+        public void onPartitionsAssigned(Collection<TopicPartition> partitions) {
+            log.debug("onPartitionsAssigned: {} from topic {}", threadId, topicName);
+
+            StateRepository<String, String> offsetRepository = endpoint.getConfiguration().getOffsetRepository();
+            if (offsetRepository != null) {
+                for (TopicPartition partition : partitions) {
+                    String offsetState = offsetRepository.getState(serializeOffsetKey(partition));
+                    if (offsetState != null && !offsetState.isEmpty()) {
+                        // The state contains the last read offset so you need to seek from the next one
+                        long offset = deserializeOffsetValue(offsetState) + 1;
+                        log.debug("Resuming partition {} from offset {} from state", partition.partition(), offset);
+                        consumer.seek(partition, offset);
+                    }
+                }
+            }
+        }
     }
 
     private boolean isAutoCommitEnabled() {
diff --git a/components/camel-kafka/src/test/java/org/apache/camel/component/kafka/KafkaConsumerTopicIsPatternTest.java b/components/camel-kafka/src/test/java/org/apache/camel/component/kafka/KafkaConsumerTopicIsPatternTest.java
new file mode 100644
index 0000000..9189bb9
--- /dev/null
+++ b/components/camel-kafka/src/test/java/org/apache/camel/component/kafka/KafkaConsumerTopicIsPatternTest.java
@@ -0,0 +1,93 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.component.kafka;
+
+import java.util.Properties;
+import java.util.stream.StreamSupport;
+
+import org.apache.camel.Endpoint;
+import org.apache.camel.EndpointInject;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.component.mock.MockEndpoint;
+import org.apache.kafka.clients.producer.ProducerRecord;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+
+public class KafkaConsumerTopicIsPatternTest extends BaseEmbeddedKafkaTest {
+
+    public static final String TOPIC = "test";
+    public static final String TOPIC_PATTERN = "t\\w\\wt";
+
+    @EndpointInject(uri = "kafka:" + TOPIC_PATTERN
+        + "?topicIsPattern=true&groupId=group1&autoOffsetReset=earliest"
+        + "&autoCommitIntervalMs=1000&sessionTimeoutMs=30000&autoCommitEnable=true&interceptorClasses=org.apache.camel.component.kafka.MockConsumerInterceptor")
+    private Endpoint from;
+
+    @EndpointInject(uri = "mock:result")
+    private MockEndpoint to;
+
+    private org.apache.kafka.clients.producer.KafkaProducer<String, String> producer;
+
+    @Before
+    public void before() {
+        Properties props = getDefaultProperties();
+        producer = new org.apache.kafka.clients.producer.KafkaProducer<String, String>(props);
+
+    }
+
+    @After
+    public void after() {
+        if (producer != null) {
+            producer.close();
+        }
+    }
+
+    @Override
+    protected RouteBuilder createRouteBuilder() throws Exception {
+        return new RouteBuilder() {
+
+            @Override
+            public void configure() throws Exception {
+                from(from).to(to);
+            }
+        };
+    }
+
+    @Test
+    public void kafkaTopicIsPattern() throws Exception {
+        to.expectedMessageCount(5);
+        to.expectedBodiesReceivedInAnyOrder("message-0", "message-1", "message-2", "message-3", "message-4");
+        to.allMessages().header(KafkaConstants.TOPIC).isEqualTo("test");
+        // The LAST_RECORD_BEFORE_COMMIT header should not be configured on any exchange because autoCommitEnable=true
+        to.expectedHeaderValuesReceivedInAnyOrder(KafkaConstants.LAST_RECORD_BEFORE_COMMIT, null, null, null, null, null);
+
+        for (int k = 0; k < 5; k++) {
+            String msg = "message-" + k;
+            ProducerRecord<String, String> data = new ProducerRecord<String, String>(TOPIC, "1", msg);
+            producer.send(data);
+        }
+
+        to.assertIsSatisfied(3000);
+
+        assertEquals(5, StreamSupport.stream(MockConsumerInterceptor.recordsCaptured.get(0).records(TOPIC).spliterator(), false).count());
+    }
+
+}
+
+
+
diff --git a/platforms/spring-boot/components-starter/camel-kafka-starter/src/main/java/org/apache/camel/component/kafka/springboot/KafkaComponentConfiguration.java b/platforms/spring-boot/components-starter/camel-kafka-starter/src/main/java/org/apache/camel/component/kafka/springboot/KafkaComponentConfiguration.java
index d7d4c83..c52e1e1 100644
--- a/platforms/spring-boot/components-starter/camel-kafka-starter/src/main/java/org/apache/camel/component/kafka/springboot/KafkaComponentConfiguration.java
+++ b/platforms/spring-boot/components-starter/camel-kafka-starter/src/main/java/org/apache/camel/component/kafka/springboot/KafkaComponentConfiguration.java
@@ -165,6 +165,11 @@ public class KafkaComponentConfiguration
     public static class KafkaConfigurationNestedConfiguration {
         public static final Class CAMEL_NESTED_CLASS = org.apache.camel.component.kafka.KafkaConfiguration.class;
         /**
+         * Whether the topic is a pattern (regular expression). This can be used
+         * to subscribe to dynamic number of topics matching the pattern.
+         */
+        private Boolean topicIsPattern = false;
+        /**
          * A string that uniquely identifies the group of consumer processes to
          * which this consumer belongs. By setting the same group id multiple
          * processes indicate that they are all part of the same consumer group.
@@ -730,6 +735,14 @@ public class KafkaComponentConfiguration
          */
         private Boolean enableIdempotence = false;
 
+        public Boolean getTopicIsPattern() {
+            return topicIsPattern;
+        }
+
+        public void setTopicIsPattern(Boolean topicIsPattern) {
+            this.topicIsPattern = topicIsPattern;
+        }
+
         public String getGroupId() {
             return groupId;
         }

-- 
To stop receiving notification emails like this one, please contact
['"commits@camel.apache.org" <co...@camel.apache.org>'].