过滤Kafka Streams

时间:2018-05-09 20:17:55

标签: java apache-kafka apache-kafka-streams

我一直在检查Kafka流。我一直在测试Kafka流的以下代码

生产者主题:(这是第一个生成主题 - 发送以下json数据)

KafkaProducer<String, String> producer = new KafkaProducer<>(
                    properties);

    producer.send(new ProducerRecord<String,String>(topic, jsonobject.toString()));
                  producer.close();

JSON - 主题制作人:

{"UserID":"1","Address”:”XXX”,”AccountNo":"234234","MemberName”:”Stella”,”AccountType":"Savings"}

流主题代码:(这是第二个流代码和主题)

builder.<String,String>stream(topic)
           .filter(new Predicate <String, String>() {
               @Override

            public boolean test(String key, String value) {

                   // put you processor logic here
                   System.out.println("value : " + value);

                   return value.substring(0).equals(“1”);
               }
            }) 
           .to(streamouttopic);

         final KafkaStreams streams = new KafkaStreams(builder, props);
         final CountDownLatch latch = new CountDownLatch(1);

            // attach shutdown handler to catch control-c
            Runtime.getRuntime().addShutdownHook(new Thread("streams-shutdown-hook") {
                @Override
                public void run() {
                    streams.close();
                    latch.countDown();
                }
            });

            try {
                streams.start();
                latch.await();
            } catch (Throwable e) {
                System.exit(1);
            }
            System.exit(0);

如果UserID值为“1”,我想要文件管理器,然后将该数据发送到目标流媒体主题。

当我使用“.filter”并打印System.out.println(&#34; value:&#34; + value);时,它会在执行时抛出以下错误。

Exception in thread "SampleStreamProducer-a6bb543e-bb92-48d0-8d9f-225046722d81-StreamThread-1" java.lang.ClassCastException: [B cannot be cast to java.lang.String

如果我不使用“.filter”并使用这样的简单代码builder.stream(topic).to(streamouttopic);,它工作正常,但没有过滤。但是,我需要使用那个过滤器。

有人可以指导我修理它吗?

1 个答案:

答案 0 :(得分:0)

默认情况下,Kafka Streams假设数据类型为<byte[],byte[]>,而byte[]无法转换为String

在阅读主题为Serdes时,您需要指定正确的KStream

builder.<String,String>stream(topic, Consumed.with(Serdes.String(), Serdes.String())
       .filter(...)

请查看示例并阅读文档:

相关问题