Filter Kafka Streams

假如想象 提交于 2019-12-11 09:15:16

问题


I have been checking Kafka streams. I have been testing the below code for Kafka streams

Producer topic: (this is the first producer topic - which sends the below json data)

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

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

JSON - Producer from topic:

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

Stream Topic code: (this is the second Streaming code and topic)

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);

I want to filer if UserID value is “1”, then send that data to destination streaming topic.

When I use “.filter” and print System.out.println("value : " + value);, it throws the below error when executing.

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

If i don’t use “.filter” and use simple code like this, builder.stream(topic).to(streamouttopic); , it is working fine, but without filtering. But, I need to use that filter.

Can someone guide me to fix it?


回答1:


By default, Kafka Streams assumes data type <byte[],byte[]> and a byte[] cannot be cast to a String.

You need to specify the correct Serdes when reading the topic as KStream:

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

Please check out the examples and read the docs:

  • https://github.com/confluentinc/kafka-streams-examples
  • https://kafka.apache.org/11/documentation/streams/


来源:https://stackoverflow.com/questions/50261373/filter-kafka-streams

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!