Search in sources :

Example 6 with LongDeserializer

use of org.apache.kafka.common.serialization.LongDeserializer in project kafka by apache.

the class RepartitionWithMergeOptimizingTest method runTest.

private void runTest(final String optimizationConfig, final int expectedNumberRepartitionTopics) {
    streamsConfiguration.setProperty(StreamsConfig.TOPOLOGY_OPTIMIZATION_CONFIG, optimizationConfig);
    final StreamsBuilder builder = new StreamsBuilder();
    final KStream<String, String> sourceAStream = builder.stream(INPUT_A_TOPIC, Consumed.with(Serdes.String(), Serdes.String()).withName("sourceAStream"));
    final KStream<String, String> sourceBStream = builder.stream(INPUT_B_TOPIC, Consumed.with(Serdes.String(), Serdes.String()).withName("sourceBStream"));
    final KStream<String, String> mappedAStream = sourceAStream.map((k, v) -> KeyValue.pair(v.split(":")[0], v), Named.as("mappedAStream"));
    final KStream<String, String> mappedBStream = sourceBStream.map((k, v) -> KeyValue.pair(v.split(":")[0], v), Named.as("mappedBStream"));
    final KStream<String, String> mergedStream = mappedAStream.merge(mappedBStream, Named.as("mergedStream"));
    mergedStream.groupByKey(Grouped.as("long-groupByKey")).count(Named.as("long-count"), Materialized.as(Stores.inMemoryKeyValueStore("long-store"))).toStream(Named.as("long-toStream")).to(COUNT_TOPIC, Produced.with(Serdes.String(), Serdes.Long()).withName("long-to"));
    mergedStream.groupByKey(Grouped.as("string-groupByKey")).count(Named.as("string-count"), Materialized.as(Stores.inMemoryKeyValueStore("string-store"))).toStream(Named.as("string-toStream")).mapValues(v -> v.toString(), Named.as("string-mapValues")).to(STRING_COUNT_TOPIC, Produced.with(Serdes.String(), Serdes.String()).withName("string-to"));
    final Topology topology = builder.build(streamsConfiguration);
    topologyTestDriver = new TopologyTestDriver(topology, streamsConfiguration);
    final TestInputTopic<String, String> inputTopicA = topologyTestDriver.createInputTopic(INPUT_A_TOPIC, stringSerializer, stringSerializer);
    final TestInputTopic<String, String> inputTopicB = topologyTestDriver.createInputTopic(INPUT_B_TOPIC, stringSerializer, stringSerializer);
    final TestOutputTopic<String, Long> countOutputTopic = topologyTestDriver.createOutputTopic(COUNT_TOPIC, stringDeserializer, new LongDeserializer());
    final TestOutputTopic<String, String> stringCountOutputTopic = topologyTestDriver.createOutputTopic(STRING_COUNT_TOPIC, stringDeserializer, stringDeserializer);
    inputTopicA.pipeKeyValueList(getKeyValues());
    inputTopicB.pipeKeyValueList(getKeyValues());
    final String topologyString = topology.describe().toString();
    // Verify the topology
    if (optimizationConfig.equals(StreamsConfig.OPTIMIZE)) {
        assertEquals(EXPECTED_OPTIMIZED_TOPOLOGY, topologyString);
    } else {
        assertEquals(EXPECTED_UNOPTIMIZED_TOPOLOGY, topologyString);
    }
    // Verify the number of repartition topics
    assertEquals(expectedNumberRepartitionTopics, getCountOfRepartitionTopicsFound(topologyString));
    // Verify the expected output
    assertThat(countOutputTopic.readKeyValuesToMap(), equalTo(keyValueListToMap(expectedCountKeyValues)));
    assertThat(stringCountOutputTopic.readKeyValuesToMap(), equalTo(keyValueListToMap(expectedStringCountKeyValues)));
}
Also used : StreamsBuilder(org.apache.kafka.streams.StreamsBuilder) StreamsConfig(org.apache.kafka.streams.StreamsConfig) Arrays(java.util.Arrays) Produced(org.apache.kafka.streams.kstream.Produced) CoreMatchers.equalTo(org.hamcrest.CoreMatchers.equalTo) Stores(org.apache.kafka.streams.state.Stores) LoggerFactory(org.slf4j.LoggerFactory) HashMap(java.util.HashMap) KStream(org.apache.kafka.streams.kstream.KStream) ArrayList(java.util.ArrayList) Matcher(java.util.regex.Matcher) StringDeserializer(org.apache.kafka.common.serialization.StringDeserializer) Map(java.util.Map) Named(org.apache.kafka.streams.kstream.Named) After(org.junit.After) Serdes(org.apache.kafka.common.serialization.Serdes) StringSerializer(org.apache.kafka.common.serialization.StringSerializer) Deserializer(org.apache.kafka.common.serialization.Deserializer) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) Before(org.junit.Before) TopologyTestDriver(org.apache.kafka.streams.TopologyTestDriver) StreamsBuilder(org.apache.kafka.streams.StreamsBuilder) TestOutputTopic(org.apache.kafka.streams.TestOutputTopic) Properties(java.util.Properties) Logger(org.slf4j.Logger) Consumed(org.apache.kafka.streams.kstream.Consumed) KeyValue(org.apache.kafka.streams.KeyValue) LongDeserializer(org.apache.kafka.common.serialization.LongDeserializer) Test(org.junit.Test) Grouped(org.apache.kafka.streams.kstream.Grouped) List(java.util.List) Serializer(org.apache.kafka.common.serialization.Serializer) Materialized(org.apache.kafka.streams.kstream.Materialized) TestInputTopic(org.apache.kafka.streams.TestInputTopic) StreamsTestUtils(org.apache.kafka.test.StreamsTestUtils) Pattern(java.util.regex.Pattern) Topology(org.apache.kafka.streams.Topology) Assert.assertEquals(org.junit.Assert.assertEquals) LongDeserializer(org.apache.kafka.common.serialization.LongDeserializer) TopologyTestDriver(org.apache.kafka.streams.TopologyTestDriver) Topology(org.apache.kafka.streams.Topology)

Example 7 with LongDeserializer

use of org.apache.kafka.common.serialization.LongDeserializer in project kafka by apache.

the class EosTestDriver method verifyCnt.

private static void verifyCnt(final Map<TopicPartition, List<ConsumerRecord<byte[], byte[]>>> inputPerTopicPerPartition, final Map<TopicPartition, List<ConsumerRecord<byte[], byte[]>>> cntPerTopicPerPartition) {
    final StringDeserializer stringDeserializer = new StringDeserializer();
    final LongDeserializer longDeserializer = new LongDeserializer();
    final HashMap<String, Long> currentSumPerKey = new HashMap<>();
    for (final Map.Entry<TopicPartition, List<ConsumerRecord<byte[], byte[]>>> partitionRecords : cntPerTopicPerPartition.entrySet()) {
        final TopicPartition inputTopicPartition = new TopicPartition("repartition", partitionRecords.getKey().partition());
        final List<ConsumerRecord<byte[], byte[]>> partitionInput = inputPerTopicPerPartition.get(inputTopicPartition);
        final List<ConsumerRecord<byte[], byte[]>> partitionCnt = partitionRecords.getValue();
        if (partitionInput.size() != partitionCnt.size()) {
            throw new RuntimeException("Result verification failed: expected " + partitionInput.size() + " records for " + partitionRecords.getKey() + " but received " + partitionCnt.size());
        }
        final Iterator<ConsumerRecord<byte[], byte[]>> inputRecords = partitionInput.iterator();
        for (final ConsumerRecord<byte[], byte[]> receivedRecord : partitionCnt) {
            final ConsumerRecord<byte[], byte[]> input = inputRecords.next();
            final String receivedKey = stringDeserializer.deserialize(receivedRecord.topic(), receivedRecord.key());
            final long receivedValue = longDeserializer.deserialize(receivedRecord.topic(), receivedRecord.value());
            final String key = stringDeserializer.deserialize(input.topic(), input.key());
            Long cnt = currentSumPerKey.get(key);
            if (cnt == null) {
                cnt = 0L;
            }
            currentSumPerKey.put(key, ++cnt);
            if (!receivedKey.equals(key) || receivedValue != cnt) {
                throw new RuntimeException("Result verification failed for " + receivedRecord + " expected <" + key + "," + cnt + "> but was <" + receivedKey + "," + receivedValue + ">");
            }
        }
    }
}
Also used : HashMap(java.util.HashMap) StringDeserializer(org.apache.kafka.common.serialization.StringDeserializer) ConsumerRecord(org.apache.kafka.clients.consumer.ConsumerRecord) LongDeserializer(org.apache.kafka.common.serialization.LongDeserializer) TopicPartition(org.apache.kafka.common.TopicPartition) ArrayList(java.util.ArrayList) LinkedList(java.util.LinkedList) List(java.util.List) HashMap(java.util.HashMap) Map(java.util.Map)

Example 8 with LongDeserializer

use of org.apache.kafka.common.serialization.LongDeserializer in project apache-kafka-on-k8s by banzaicloud.

the class KStreamAggregationDedupIntegrationTest method shouldGroupByKey.

@Test
public void shouldGroupByKey() throws Exception {
    final long timestamp = mockTime.milliseconds();
    produceMessages(timestamp);
    produceMessages(timestamp);
    stream.groupByKey(Serialized.with(Serdes.Integer(), Serdes.String())).count(TimeWindows.of(500L), "count-windows").toStream(new KeyValueMapper<Windowed<Integer>, Long, String>() {

        @Override
        public String apply(final Windowed<Integer> windowedKey, final Long value) {
            return windowedKey.key() + "@" + windowedKey.window().start();
        }
    }).to(Serdes.String(), Serdes.Long(), outputTopic);
    startStreams();
    final List<KeyValue<String, Long>> results = receiveMessages(new StringDeserializer(), new LongDeserializer(), 5);
    Collections.sort(results, new Comparator<KeyValue<String, Long>>() {

        @Override
        public int compare(final KeyValue<String, Long> o1, final KeyValue<String, Long> o2) {
            return KStreamAggregationDedupIntegrationTest.compare(o1, o2);
        }
    });
    final long window = timestamp / 500 * 500;
    assertThat(results, is(Arrays.asList(KeyValue.pair("1@" + window, 2L), KeyValue.pair("2@" + window, 2L), KeyValue.pair("3@" + window, 2L), KeyValue.pair("4@" + window, 2L), KeyValue.pair("5@" + window, 2L))));
}
Also used : KeyValue(org.apache.kafka.streams.KeyValue) StringDeserializer(org.apache.kafka.common.serialization.StringDeserializer) KeyValueMapper(org.apache.kafka.streams.kstream.KeyValueMapper) Windowed(org.apache.kafka.streams.kstream.Windowed) LongDeserializer(org.apache.kafka.common.serialization.LongDeserializer) IntegrationTest(org.apache.kafka.test.IntegrationTest) Test(org.junit.Test)

Example 9 with LongDeserializer

use of org.apache.kafka.common.serialization.LongDeserializer in project apache-kafka-on-k8s by banzaicloud.

the class KStreamAggregationIntegrationTest method shouldGroupByKey.

@Test
public void shouldGroupByKey() throws Exception {
    final long timestamp = mockTime.milliseconds();
    produceMessages(timestamp);
    produceMessages(timestamp);
    stream.groupByKey(Serialized.with(Serdes.Integer(), Serdes.String())).windowedBy(TimeWindows.of(500L)).count().toStream(new KeyValueMapper<Windowed<Integer>, Long, String>() {

        @Override
        public String apply(final Windowed<Integer> windowedKey, final Long value) {
            return windowedKey.key() + "@" + windowedKey.window().start();
        }
    }).to(outputTopic, Produced.with(Serdes.String(), Serdes.Long()));
    startStreams();
    final List<KeyValue<String, Long>> results = receiveMessages(new StringDeserializer(), new LongDeserializer(), 10);
    Collections.sort(results, new Comparator<KeyValue<String, Long>>() {

        @Override
        public int compare(final KeyValue<String, Long> o1, final KeyValue<String, Long> o2) {
            return KStreamAggregationIntegrationTest.compare(o1, o2);
        }
    });
    final long window = timestamp / 500 * 500;
    assertThat(results, is(Arrays.asList(KeyValue.pair("1@" + window, 1L), KeyValue.pair("1@" + window, 2L), KeyValue.pair("2@" + window, 1L), KeyValue.pair("2@" + window, 2L), KeyValue.pair("3@" + window, 1L), KeyValue.pair("3@" + window, 2L), KeyValue.pair("4@" + window, 1L), KeyValue.pair("4@" + window, 2L), KeyValue.pair("5@" + window, 1L), KeyValue.pair("5@" + window, 2L))));
}
Also used : KeyValue(org.apache.kafka.streams.KeyValue) StringDeserializer(org.apache.kafka.common.serialization.StringDeserializer) KeyValueMapper(org.apache.kafka.streams.kstream.KeyValueMapper) Windowed(org.apache.kafka.streams.kstream.Windowed) LongDeserializer(org.apache.kafka.common.serialization.LongDeserializer) IntegrationTest(org.apache.kafka.test.IntegrationTest) Test(org.junit.Test)

Example 10 with LongDeserializer

use of org.apache.kafka.common.serialization.LongDeserializer in project sda-dropwizard-commons by SDA-SE.

the class KafkaBundleWithConfigIT method multiTest.

@Test
public void multiTest() {
    final String TOPIC_CREATE = "create";
    final String TOPIC_DELETE = "delete";
    KAFKA.getKafkaTestUtils().createTopic(TOPIC_CREATE, 1, (short) 1);
    KAFKA.getKafkaTestUtils().createTopic(TOPIC_DELETE, 1, (short) 1);
    kafkaBundle.createMessageListener(MessageListenerRegistration.builder().withDefaultListenerConfig().forTopic(TOPIC_CREATE).withDefaultConsumer().withKeyDeserializer(new LongDeserializer()).withListenerStrategy(new SyncCommitMLS<Long, String>(record -> resultsString.add(record.value()), new IgnoreAndProceedErrorHandler<>())).build());
    kafkaBundle.createMessageListener(MessageListenerRegistration.builder().withDefaultListenerConfig().forTopic(TOPIC_DELETE).withDefaultConsumer().withListenerStrategy(new SyncCommitMLS<String, String>(record -> resultsString.add(record.value()), new IgnoreAndProceedErrorHandler<>())).build());
    MessageProducer<Long, String> createProducer = kafkaBundle.registerProducer(ProducerRegistration.<Long, String>builder().forTopic(TOPIC_CREATE).withProducerConfig(new ProducerConfig()).withKeySerializer(new LongSerializer()).build());
    MessageProducer<String, String> deleteProducer = kafkaBundle.registerProducer(ProducerRegistration.<String, String>builder().forTopic(TOPIC_DELETE).withDefaultProducer().build());
    createProducer.send(1L, "test1");
    deleteProducer.send("key", "test2");
    await().atMost(KafkaBundleConsts.N_MAX_WAIT_MS, MILLISECONDS).until(() -> resultsString.size() == 2);
    assertThat(resultsString).containsExactlyInAnyOrder("test1", "test2");
}
Also used : AutocommitMLS(org.sdase.commons.server.kafka.consumer.strategies.autocommit.AutocommitMLS) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) MessageListenerRegistration(org.sdase.commons.server.kafka.builder.MessageListenerRegistration) ListenerConfig(org.sdase.commons.server.kafka.config.ListenerConfig) ConsumerRecords(org.apache.kafka.clients.consumer.ConsumerRecords) KafkaHelper(org.sdase.commons.server.kafka.consumer.KafkaHelper) MessageListenerStrategy(org.sdase.commons.server.kafka.consumer.strategies.MessageListenerStrategy) StringDeserializer(org.apache.kafka.common.serialization.StringDeserializer) Map(java.util.Map) StringSerializer(org.apache.kafka.common.serialization.StringSerializer) ClassRule(org.junit.ClassRule) KafkaJsonSerializer(org.sdase.commons.server.kafka.serializers.KafkaJsonSerializer) TopicPartition(org.apache.kafka.common.TopicPartition) Awaitility.await(org.awaitility.Awaitility.await) AfterClass(org.junit.AfterClass) Set(java.util.Set) LongDeserializer(org.apache.kafka.common.serialization.LongDeserializer) MILLISECONDS(java.util.concurrent.TimeUnit.MILLISECONDS) UUID(java.util.UUID) LongSerializer(org.apache.kafka.common.serialization.LongSerializer) List(java.util.List) ConsumerConfig(org.sdase.commons.server.kafka.config.ConsumerConfig) ConfigOverride.config(io.dropwizard.testing.ConfigOverride.config) ConsumerRecord(org.apache.kafka.clients.consumer.ConsumerRecord) IgnoreAndProceedErrorHandler(org.sdase.commons.server.kafka.consumer.IgnoreAndProceedErrorHandler) KafkaConsumer(org.apache.kafka.clients.consumer.KafkaConsumer) ProducerConfig(org.sdase.commons.server.kafka.config.ProducerConfig) ProducerRecord(org.apache.kafka.clients.producer.ProducerRecord) BeforeClass(org.junit.BeforeClass) TestRule(org.junit.rules.TestRule) SharedKafkaTestResource(com.salesforce.kafka.test.junit4.SharedKafkaTestResource) KafkaJsonDeserializer(org.sdase.commons.server.kafka.serializers.KafkaJsonDeserializer) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) WrappedNoSerializationErrorDeserializer(org.sdase.commons.server.kafka.serializers.WrappedNoSerializationErrorDeserializer) KafkaProducer(org.apache.kafka.clients.producer.KafkaProducer) DropwizardAppRule(io.dropwizard.testing.junit.DropwizardAppRule) KafkaTestApplication(org.sdase.commons.server.kafka.dropwizard.KafkaTestApplication) ConfigurationException(org.sdase.commons.server.kafka.exception.ConfigurationException) ProducerRegistration(org.sdase.commons.server.kafka.builder.ProducerRegistration) SyncCommitMLS(org.sdase.commons.server.kafka.consumer.strategies.synccommit.SyncCommitMLS) Before(org.junit.Before) ErrorHandler(org.sdase.commons.server.kafka.consumer.ErrorHandler) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) Test(org.junit.Test) MessageHandler(org.sdase.commons.server.kafka.consumer.MessageHandler) RuleChain(org.junit.rules.RuleChain) AtomicLong(java.util.concurrent.atomic.AtomicLong) MessageProducer(org.sdase.commons.server.kafka.producer.MessageProducer) ResourceHelpers.resourceFilePath(io.dropwizard.testing.ResourceHelpers.resourceFilePath) MessageListener(org.sdase.commons.server.kafka.consumer.MessageListener) KafkaTestConfiguration(org.sdase.commons.server.kafka.dropwizard.KafkaTestConfiguration) Collections(java.util.Collections) SimpleEntity(org.sdase.commons.server.kafka.serializers.SimpleEntity) LongSerializer(org.apache.kafka.common.serialization.LongSerializer) LongDeserializer(org.apache.kafka.common.serialization.LongDeserializer) IgnoreAndProceedErrorHandler(org.sdase.commons.server.kafka.consumer.IgnoreAndProceedErrorHandler) AtomicLong(java.util.concurrent.atomic.AtomicLong) ProducerConfig(org.sdase.commons.server.kafka.config.ProducerConfig) Test(org.junit.Test)

Aggregations

LongDeserializer (org.apache.kafka.common.serialization.LongDeserializer)37 StringDeserializer (org.apache.kafka.common.serialization.StringDeserializer)33 KeyValue (org.apache.kafka.streams.KeyValue)22 Test (org.junit.Test)22 StringSerializer (org.apache.kafka.common.serialization.StringSerializer)20 List (java.util.List)19 Properties (java.util.Properties)18 StreamsBuilder (org.apache.kafka.streams.StreamsBuilder)16 HashMap (java.util.HashMap)14 Arrays (java.util.Arrays)13 Map (java.util.Map)13 Serdes (org.apache.kafka.common.serialization.Serdes)13 StreamsConfig (org.apache.kafka.streams.StreamsConfig)13 TopologyTestDriver (org.apache.kafka.streams.TopologyTestDriver)12 KStream (org.apache.kafka.streams.kstream.KStream)12 ArrayList (java.util.ArrayList)11 IntegerDeserializer (org.apache.kafka.common.serialization.IntegerDeserializer)11 Consumed (org.apache.kafka.streams.kstream.Consumed)10 Produced (org.apache.kafka.streams.kstream.Produced)10 Deserializer (org.apache.kafka.common.serialization.Deserializer)9