KStream-KTable连接写入KTable:如何将连接与ktable写入同步?

时间:2017-09-14 13:37:22

标签: apache-kafka-streams

我遇到以下拓扑行为的问题:

String topic = config.topic();

KTable<UUID, MyData> myTable = topology.builder().table(UUIDSerdes.get(), GsonSerdes.get(MyData.class), topic);

// Receive a stream of various events
topology.eventsStream()
    // Only process events that are implementing MyEvent
    .filter((k, v) -> v instanceof MyEvent)
    // Cast to ease the code
    .mapValues(v -> (MyEvent) v)
    // rekey by data id
    .selectKey((k, v) -> v.data.id)
    .peek((k, v) -> L.info("Event:"+v.action))
    // join the event with the according entry in the KTable and apply the state mutation
    .leftJoin(myTable, eventHandler::handleEvent, UUIDSerdes.get(), EventSerdes.get())
    .peek((k, v) -> L.info("Updated:" + v.id + "-" + v.id2))
    // write the updated state to the KTable.
    .to(UUIDSerdes.get(), GsonSerdes.get(MyData.class), topic);

我的问题发生在我同时收到不同的事件时。由于我的状态变异由leftJoin完成,然后由to方法编写。如果使用相同的密钥同时收到事件1和2,我可以发生以下情况:

event1 joins with state A => state A mutated to state X
event2 joins with state A => state A mutated to state Y
state X written to the KTable topic
state Y written to the KTable topic

因此,状态Y没有event1的更改,因此我丢失了数据。

以下是我所看到的日志(Processing:...部分是从值连接器内部记录的):

Event:Event1
Event:Event2
Processing:Event1, State:none
Updated:1-null
Processing:Event2, State:none
java.lang.IllegalStateException: Event2 event received but we don't have data for id 1

Event1可以被视为创建事件:它将在KTable中创建条目,因此状态为空是无关紧要的。 Event2虽然需要将其更改应用于现有状态,但它找不到任何因为第一个状态变异仍未写入KTable(它仍然没有被{{1}处理方法)

无论如何要确保我的leftJoin和我写入ktable的内容是原子地完成的吗?

由于

更新&amp;当前的解决方案

感谢@Matthias的回复,我能够使用to找到解决方案。

这是代码的样子:

那是变压器

Transformer

这是改编的拓扑结构:

public class KStreamStateLeftJoin<K, V1, V2> implements Transformer<K, V1, KeyValue<K, V2>> {

    private final String                    stateName;
    private final ValueJoiner<V1, V2, V2>   joiner;
    private final boolean                   updateState;

    private KeyValueStore<K, V2>            state;

    public KStreamStateLeftJoin(String stateName, ValueJoiner<V1, V2, V2> joiner, boolean updateState) {
        this.stateName = stateName;
        this.joiner = joiner;
        this.updateState = updateState;
    }

    @Override
    @SuppressWarnings("unchecked")
    public void init(ProcessorContext context) {
        this.state = (KeyValueStore<K, V2>) context.getStateStore(stateName);
    }

    @Override
    public KeyValue<K, V2> transform(K key, V1 value) {
        V2 stateValue = this.state.get(key); // Get current state
        V2 updatedValue = joiner.apply(value, stateValue); // Apply join
        if (updateState) {
            this.state.put(key, updatedValue); // write new state
        }
        return new KeyValue<>(key, updatedValue);
    }

    @Override
    public KeyValue<K, V2> punctuate(long timestamp) {
        return null;
    }

    @Override
    public void close() {}
}

当我们使用KTable的KV StateStore并通过String topic = config.topic(); String store = topic + "-store"; KTable<UUID, MyData> myTable = topology.builder().table(UUIDSerdes.get(), GsonSerdes.get(MyData.class), topic, store); // Receive a stream of various events topology.eventsStream() // Only process events that are implementing MyEvent .filter((k, v) -> v instanceof MyEvent) // Cast to ease the code .mapValues(v -> (MyEvent) v) // rekey by data id .selectKey((k, v) -> v.data.id) // join the event with the according entry in the KTable and apply the state mutation .transform(() -> new KStreamStateLeftJoin<UUID, MyEvent, MyData>(store, eventHandler::handleEvent, true), store) // write the updated state to the KTable. .to(UUIDSerdes.get(), GsonSerdes.get(MyData.class), topic); 方法事件直接在其中应用更改时,shoudl始终会获取更新后的状态。 有一点我还在想:如果我有持续的高吞吐量事件怎么办。

我们在KTable的KV商店和KTable主题中的写入之间是否存在竞争条件?

1 个答案:

答案 0 :(得分:4)

KTable分片为多个物理存储,每个存储仅由单个线程更新。因此,您描述的场景不可能发生。如果您有2条具有相同时间戳的记录,它们都会更新相同的分片,则它们将一个接一个地处理(按偏移顺序)。因此,第二次更新将看到第一次更新后的状态。

所以也许你刚才没有正确描述你的情景?

<强>更新

进行连接时不能改变状态。因此,期望

event1 joins with state A => state A mutated to state X

错了。独立于任何处理订单,当event1加入state A时,它将以只读模式访问state Astate A将不会被修改。

因此,当event2加入时,它将看到与event1相同的状态。对于流表连接,只有在从table-input-topic读取新数据时才更新表状态。

如果您希望从两个输入更新共享状态,则需要使用transform()构建自定义解决方案:

builder.addStore(..., "store-name");
builder.stream("table-topic").transform(..., "store-name"); // will not emit anything downstream
KStream result = builder.stream("stream-topic").transform(..., "store-name");

这将创建一个由两个处理器共享的存储,并且两者都可以根据需要进行读/写。因此,对于表输入,您只需更新状态而不向下游发送任何内容,而对于流输入,您可以执行连接,更新状态并向下游发送结果。

更新2

关于解决方案,Transformer应用于状态的更新之间不存在竞争条件,并且在状态更新之后记录Transformer进程。此部分将在单个线程中执行,记录将按输入主题的偏移顺序处理。因此,确保状态更新可用于以后的记录。

相关问题