Kafka Streams 2.1.1 class cast while flushing time

2019-04-15 02:35发布

问题:

I'm trying to use kafka streams to perform a windowed aggregation and emit the result only after a certain session window is closed. To achieve this I'm using the suppress function.

The problem is that I don't find a way to make this simple test work because when it tries to persist the state I get a class cast exception because it tries to cast Windowed to String. I have tried to provide to the aggregate function a Materialized<Windowed<String>,Long,StateStore<>> but it doesn't type check because it expects the first type to be simply string.

What am I missing here?

kafka version 2.1.1

package test;

import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.streams.KeyValue;
import org.apache.kafka.streams.StreamsBuilder;
import org.apache.kafka.streams.StreamsConfig;
import org.apache.kafka.streams.Topology;
import org.apache.kafka.streams.TopologyTestDriver;
import org.apache.kafka.streams.kstream.KStream;
import org.apache.kafka.streams.kstream.SessionWindows;
import org.apache.kafka.streams.kstream.Suppressed;
import org.apache.kafka.streams.test.ConsumerRecordFactory;
import org.junit.Test;

import java.text.MessageFormat;
import java.time.Duration;
import java.util.Properties;

public class TestAggregation {

    @Test
    public void aggregationTest() {
        StreamsBuilder streamsBuilder = new StreamsBuilder();
        KStream<String, Long> input = streamsBuilder.stream("input");

        input
            .groupByKey()
            .windowedBy(SessionWindows.with(Duration.ofSeconds(30)))
            .aggregate(() -> Long.valueOf(0), (key, v1, v2) -> v1 + v2, (key, agg1, agg2) -> agg1 + agg2)
            .suppress(Suppressed.untilWindowCloses(Suppressed.BufferConfig.unbounded()))
            .toStream()
            .map((k, v) -> new KeyValue<>(k.key(), v))
            .to("output");

        Topology topology = streamsBuilder.build();

        Properties props = new Properties();
        props.put(StreamsConfig.APPLICATION_ID_CONFIG, "test");
        props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "dummy:1234");
        props.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass().getName());
        props.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, Serdes.Long().getClass().getName());

        TopologyTestDriver testDriver = new TopologyTestDriver(topology, props);

        ConsumerRecordFactory<String, Long> producer =
            new ConsumerRecordFactory<>("input", Serdes.String().serializer(), Serdes.Long().serializer());

        testDriver.pipeInput(producer.create("input", "key", 10L));

        ProducerRecord<String, Long> output = testDriver.readOutput("output", Serdes.String().deserializer(), Serdes.Long().deserializer());
        System.out.println(MessageFormat.format("output: k: {0}, v:{1}", output.key(), output.value()));
    }
}

And this is the stacktrace that I get out of it

17:05:38.925 [main] DEBUG org.apache.kafka.streams.processor.internals.StreamTask - task [0_0] Committing
17:05:38.925 [main] DEBUG org.apache.kafka.streams.processor.internals.ProcessorStateManager - task [0_0] Flushing all stores registered in the state manager
17:05:38.929 [main] ERROR org.apache.kafka.streams.processor.internals.ProcessorStateManager - task [0_0] Failed to flush state store KSTREAM-AGGREGATE-STATE-STORE-0000000001: 
java.lang.ClassCastException: org.apache.kafka.streams.kstream.Windowed cannot be cast to java.lang.String
    at org.apache.kafka.common.serialization.StringSerializer.serialize(StringSerializer.java:28)
    at org.apache.kafka.streams.kstream.internals.suppress.KTableSuppressProcessor.buffer(KTableSuppressProcessor.java:86)
    at org.apache.kafka.streams.kstream.internals.suppress.KTableSuppressProcessor.process(KTableSuppressProcessor.java:78)
    at org.apache.kafka.streams.kstream.internals.suppress.KTableSuppressProcessor.process(KTableSuppressProcessor.java:37)
    at org.apache.kafka.streams.processor.internals.ProcessorNode.process(ProcessorNode.java:117)
    at org.apache.kafka.streams.processor.internals.ProcessorContextImpl.forward(ProcessorContextImpl.java:146)
    at org.apache.kafka.streams.processor.internals.ProcessorContextImpl.forward(ProcessorContextImpl.java:129)
    at org.apache.kafka.streams.processor.internals.ProcessorContextImpl.forward(ProcessorContextImpl.java:93)
    at org.apache.kafka.streams.kstream.internals.ForwardingCacheFlushListener.apply(ForwardingCacheFlushListener.java:42)
    at org.apache.kafka.streams.state.internals.CachingSessionStore.putAndMaybeForward(CachingSessionStore.java:179)
    at org.apache.kafka.streams.state.internals.CachingSessionStore.access$000(CachingSessionStore.java:37)
    at org.apache.kafka.streams.state.internals.CachingSessionStore$1.apply(CachingSessionStore.java:86)
    at org.apache.kafka.streams.state.internals.NamedCache.flush(NamedCache.java:141)
    at org.apache.kafka.streams.state.internals.NamedCache.flush(NamedCache.java:99)
    at org.apache.kafka.streams.state.internals.ThreadCache.flush(ThreadCache.java:124)
    at org.apache.kafka.streams.state.internals.CachingSessionStore.flush(CachingSessionStore.java:198)
    at org.apache.kafka.streams.state.internals.MeteredSessionStore.flush(MeteredSessionStore.java:191)
    at org.apache.kafka.streams.processor.internals.ProcessorStateManager.flush(ProcessorStateManager.java:217)
    at org.apache.kafka.streams.processor.internals.AbstractTask.flushState(AbstractTask.java:204)
    at org.apache.kafka.streams.processor.internals.StreamTask.flushState(StreamTask.java:491)
    at org.apache.kafka.streams.processor.internals.StreamTask.commit(StreamTask.java:443)
    at org.apache.kafka.streams.processor.internals.StreamTask.commit(StreamTask.java:431)
    at org.apache.kafka.streams.TopologyTestDriver.pipeInput(TopologyTestDriver.java:405)
    at test.TestAggregation.aggregationTest(TestAggregation.java:49)

回答1:

There two option to solve that issue:

  1. use TimeWindowedKStream::aggregate(final Initializer<VR> initializer, final Aggregator<? super K, ? super V, VR> aggregator, final Materialized<K, VR, WindowStore<Bytes, byte[]>> materialized);

  2. use KStream::groupByKey(final Grouped<K, V> grouped)

In you case it will be:

Ad 1:

input
    .groupByKey()
    .windowedBy(SessionWindows.with(Duration.ofSeconds(30)))
    .aggregate(() -> Long.valueOf(0), (key, v1, v2) -> v1 + v2, (key, agg1, agg2) -> agg1 + agg2, Materialized.with(Serdes.String(), Serdes.Long()))
    .suppress(Suppressed.untilWindowCloses(Suppressed.BufferConfig.unbounded()))
    .toStream()
    .map((k, v) -> new KeyValue<>(k.key(), v))
    .to("output");

Ad 2:

input
    .groupByKey(Grouped.with(Serdes.String(), Serdes.Long())
    .windowedBy(SessionWindows.with(Duration.ofSeconds(30)))
    .aggregate(() -> Long.valueOf(0), (key, v1, v2) -> v1 + v2, (key, agg1, agg2) -> agg1 + agg2)
    .suppress(Suppressed.untilWindowCloses(Suppressed.BufferConfig.unbounded()))
    .toStream()
    .map((k, v) -> new KeyValue<>(k.key(), v))
    .to("output");