我的应用程序需要管理3种类型的事件:创建,编辑和删除。我可以用一个ReadSideProcessor来管理所有这些事件吗?在prepare方法中,语句的准备有什么特别的顺序吗?
是的,ReadSideProcessor.defineEventHandlers接受一个可以容纳多个事件的构建器。
由于所有事件都是唯一的,因此定义它们的顺序并不重要。把它想象成一个hashmap(事件,视图-存储逻辑)
见下文,
@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();
}
https://github.com/khazzz/lagomk
查看blog-impl项目BlogEventProcessor类。