如何使用KeyValueMapper将输入KStream <string,string>映射到<string,carclass =“”>?

时间:2017-06-01 16:29:56

标签: apache-kafka apache-kafka-streams

接收我想在CarClass上映射的Json数据并想要创建新的流但是map方法不允许我在自定义数据类型上映射 KStream类型中的方法映射(KeyValueMapper&gt;)不适用于参数(new KeyValueMapper&gt;(){})?

1 个答案:

答案 0 :(得分:4)

来自http://docs.confluent.io/current/streams/developer-guide.html#stateless-transformations

该示例将值类型从byte[]更改为IntegerStringCarClass的内容是相同的。

KStream<byte[], String> stream = ...;

// Java 8+ example, using lambda expressions
// Note how we change the key and the key type (similar to `selectKey`)
// as well as the value and the value type.
KStream<String, Integer> transformed = stream.map(
  (key, value) -> KeyValue.pair(value.toLowerCase(), value.length()));

// Java 7 example
KStream<String, Integer> transformed = stream.map(
  new KeyValueMapper<byte[], String, KeyValue<String, Integer>>() {
    @Override
    public KeyValue<String, Integer> apply(byte[] key, String value) {
      return new KeyValue<>(value.toLowerCase(), value.length());
    }
  });

但是,如果您只想修改该值,我建议您使用mapValues()代替map()