0

我的应用程序需要管理 3 种类型的事件:创建、编辑和删除。我可以只用一个 ReadSideProcessor 管理所有这些事件吗?我应该在准备方法中准备语句吗?

4

2 回答 2

0

是的,ReadSideProcessor.defineEventHandlers 接受一个可以容纳多个事件的构建器。

由于所有事件都是唯一的,因此定义它们的顺序并不重要。想想是作为一个哈希图(事件,视图存储逻辑)

见下文,

@Override
public EventHandlers defineEventHandlers(EventHandlersBuilder builder) {
    // when Account created, insert account table;
    builder.setEventHandler(TransactionEvent.AccountCreatedEvent.class, (ev, offset) -> {
        System.out.println("offset ->" + offset);
        BoundStatement st = writeAccount.bind()
                                        .setString("account_id", ev.id)
                                        .setString("name", ev.name);


        BoundStatement stOffset = writeOffset.bind(offset);

        return completedStatements(Arrays.asList(st, stOffset));
    });
    // when Deposit, insert history and update balance
    builder.setEventHandler(TransactionEvent.MoneyDepositedEvent.class, (ev, offset) -> {
        System.out.println("offset ->" + offset);
        BoundStatement historyInsert = writeHistory.bind()
                                                   .setString("account_id", ev.id)
                                                   .setLong("amount", ev.amount)
                                                   .setString("type", "DEPOSIT")
                                                   .setTimestamp("at", toTimestamp(offset));

        BoundStatement accountUpdate = updateAccount.bind()
                                                    .setString("account_id", ev.id)
                                                    .setLong("balance", ev.balance + ev.amount);

        return completedStatements(Arrays.asList(historyInsert, accountUpdate, writeOffset.bind(offset)));
    });

    // when Withdrawal, insert history and update balance
    builder.setEventHandler(TransactionEvent.MoneyWithdrawnEvent.class, (ev, offset) -> {
        System.out.println("offset ->" + offset);
        BoundStatement historyInsert = writeHistory.bind()
                                                   .setString("account_id", ev.id)
                                                   .setLong("amount", ev.amount)
                                                   .setString("type", "WITHDRAWAL")
                                                   .setTimestamp("at", toTimestamp(offset));

        BoundStatement accountUpdate = updateAccount.bind()
                                                    .setString("account_id", ev.id)
                                                    .setLong("balance", ev.balance - ev.amount);

        return completedStatements(Arrays.asList(historyInsert, accountUpdate, writeOffset.bind(offset)));
    });
    return builder.build();
}
于 2016-07-13T15:42:34.523 回答
0

https://github.com/khazzz/lagomk

查看 blog-impl 项目 BlogEventProcessor 类。

于 2019-01-24T22:09:28.367 回答