我想从KStream实例化一个KTable,并且希望KeyValueStore由Key排序。
我尝试查找KTable API规范(https://kafka.apache.org/20/javadoc/org/apache/kafka/streams/kstream/KTable.html),但是不存在“排序”方法。我还查阅了这篇文章(https://dzone.com/articles/how-to-order-streamed-dataframes),该文章建议通过Processor API实现排序。但是,我正在检查是否可以通过其他方式实现?
答案 0 :(得分:1)
使用键将事件添加到StateStore。 StateStore返回的KeyValueIterator以有序方式导航KeyValue。
public class SortProcessor extends AbstractProcessor<String, Event> {
private static Logger LOG = LoggerFactory.getLogger(SortProcessor.class);
private final String stateStore;
private final Long bufferIntervalInSeconds;
// Why not use a simple Java NavigableMap? Check out my answer at : https://stackoverflow.com/a/62677079/2256618
private KeyValueStore<String, Event> keyValueStore;
public SortProcessor(String stateStore, Long bufferIntervalInSeconds) {
this.stateStore = stateStore;
this.bufferIntervalInSeconds = bufferIntervalInSeconds;
}
@Override
public void init(ProcessorContext processorContext) {
super.init(processorContext);
keyValueStore = (KeyValueStore) context().getStateStore(stateStore);
context().schedule(Duration.ofSeconds(bufferIntervalInSeconds), PunctuationType.WALL_CLOCK_TIME, this::punctuate);
}
void punctuate(long timestamp) {
LOG.info("Punctuator invoked...");
try (KeyValueIterator<String, Event> iterator = keyValueStore.all()) {
while (iterator.hasNext()) {
KeyValue<String, Event> next = iterator.next();
if (next.value == null) {
continue;
}
LOG.info("Sending {}", next.key);
context().forward(null, next.value);
keyValueStore.delete(next.key);
}
}
}
@Override
public void process(String key, Event value) {
Event event = Event.builder(value).payload(value.getPayload().toUpperCase()).build();
keyValueStore.put(event.getEventType().name() + " " + event.getId(), event);
}
public static String getName() {
return "sort-processor";
}
}
可执行代码为here。我在这里使用了一个简单的内存状态存储。如果您预计会突然发生大量事件,则可以使用其他答案中已经建议的持久状态存储。
答案 1 :(得分:0)
KafkaStream允许您实现可查询状态存储。
然后,您可以通过调用方法kafkaStream#store()
获得对商店的只读访问权限。
如果您定义持久存储,KafkaStreams将使用RocksDB来存储您的数据。返回的KeyValueIterator实例将使用RocksDB迭代器,该迭代器将允许您以排序方式Rocks Iterator-Implementation遍历键值。
示例:
KafkaStreams streams = new KafkaStreams(topology, props);
ReadOnlyKeyValueStore<Object, Object> store = streams.store("storeName", QueryableStoreTypes.keyValueStore());
KeyValueIterator<Object, Object> iterator = store.all();