java 根据值创建计数金额的Kafka流

a64a0gku  于 2023-01-15  发布在  Java
关注(0)|答案(2)|浏览(101)

我产生的数据如下:

Key: "Mike", value: {"amount":46,"time":"2021-11-05T07:53:32.005751Z"}
Key: "John", value: {"amount":46,"time":"2021-11-05T07:53:32.005751Z"}
Key: "Mike", value: {"amount":50,"time":"2021-11-05T07:53:32.005751Z"}

关键字是字符串(名称如爱丽丝,约翰...).例如,我需要在结果:

{"Mike": 2}
{"John": 1}

{"key":"Mike", "count": 2}
{"key":"John", "count": 1}

我接着试了试:

public Topology createTopology(){
    StreamsBuilder builder = new StreamsBuilder();
    // json Serde
    final Serializer<JsonNode> jsonSerializer = new JsonSerializer();
    final Deserializer<JsonNode> jsonDeserializer = new JsonDeserializer();
    final Serde<JsonNode> jsonSerde = Serdes.serdeFrom(jsonSerializer, jsonDeserializer);

    KStream<String, JsonNode> textLines = builder.stream("bank-transactions", Consumed.with(Serdes.String(), jsonSerde));
    KTable<String, Long> wordCounts = textLines
            .map((k, v) -> new KeyValue<>(k, v.get("amount").asInt()))
            .groupByKey(Serialized.with(Serdes.String(), Serdes.Integer()))
            .count();

    wordCounts.toStream().to("person-transaction-frequency", Produced.with(Serdes.String(), Serdes.Long()));

    return builder.build();
}

public static void main(String[] args) {
    Properties config = new Properties();
    config.put(StreamsConfig.APPLICATION_ID_CONFIG, "bank-favorite-amount-application");
    config.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "127.0.0.1:29092");
    config.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
    config.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass());
    config.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, Serdes.String().getClass());

    Mc4CalculateFavoriteAmount wordCountApp = new Mc4CalculateFavoriteAmount();

    KafkaStreams streams = new KafkaStreams(wordCountApp.createTopology(), config);
    streams.start();

    // shutdown hook to correctly close the streams application
    Runtime.getRuntime().addShutdownHook(new Thread(streams::close));
}

我正试着用名字来计算消息。但是我在主题中得到了人工制品:

ctehm74n

ctehm74n1#

如果您只是想计算键数,那么可以丢弃整个值,并将其替换为1,表示所看到的每个键。

KStream<String, Bytes> textLines = builder.stream("bank-transactions", Consumed.with(Serdes.String(), Serdes.Bytes()));
KTable<String, Long> wordCounts = textLines
        .mapValues(v -> 1L)
        .groupByKey(Serialized.with(Serdes.String(), Serdes.Long()))
        .count();

wordCounts.toStream().to("person-transaction-frequency", Produced.with(Serdes.String(), Serdes.Long()));
l3zydbqr

l3zydbqr2#

您可以根据您的用例修改这个official Confluent Example。这个示例与您所问的非常相似。
为了进一步解释这一点,您需要创建一个流应用程序,在其中将数据从主题读入KStream。您还没有提供有关键的信息。在Confluent示例中,记录是使用map()方法显式重新分区的。为每条记录创建一个新的KeyValue示例(你可以用amount作为键),然后事件按键分组并计数。

相关问题