我正在尝试使用Martin Fowler所描述的使用Event Sourcing和Retroactive模式的有效代码。
我对事件如何排队有点迷茫?因为事件是逐个发送到EventProcessor的进程和反向函数。他在文章中说EventProcessor类可以访问事件队列。
但是如果我/他的EventProcessor类看起来像这样
public class DomainEventProcessor {
public void process(DomainEvent domainEvent) {
if (domainEvent instanceof ReplacementEvent) {
processReplacement((ReplacementEvent)domainEvent);
} else {
domainEvent.process();
}
}
public void reverse(DomainEvent domainEvent) {
domainEvent.reverse();
}
/*
// replace the event in event queue
*/
private void processReplacement(ReplacementEvent e) {
}
}
域事件接口
public abstract class DomainEvent implements Serializable {
public abstract void process();
public abstract void reverse();
}
示例实现事件如下所示
public class BalanceUpdateEvent extends DomainEvent {
private String subscriberId;
private String balanceId;
private Long delta;
public String getSubscriberId() {
return subscriberId;
}
public String getBalanceId() {
return balanceId;
}
public Long getDelta() {
return delta;
}
@Override
public void process() {
// do nothing
}
@Override
public void reverse() {
SubscriberDomain subscriberDomain = SubscriberAggregate.getSubscriber(subscriberId);
subscriberDomain.handleReverseEvent(this);
}
}
每个事件都知道哪个域对象(具有状态+业务逻辑)可以自行处理以更改域对象状态。
答案 0 :(得分:0)
public class DomainEventProcessor {
private EventStore es;
public DomainEventProcessor(EventStore es) {
this.es = es;
}
public void replay(String aggregateId,Date after) {
List<DomainEvent> events = es.loadEventStreamAfter(aggregateId,after);
events.sort(Comparator.comparing(DomainEvent::getTimestamp));
for(DomainEvent event : events) {
if (event instanceof ReplacementEvent) {
ReplacementEvent re = (ReplacementEvent)event;
re.getReplacement().process();
} else {
event.process();
}
}
}
public void reverse(String aggregateId,Date after) {
List<DomainEvent> events = es.loadEventStreamAfter(aggregateId,after);
events.sort(Comparator.comparing(DomainEvent::getTimestamp).reversed());
for(DomainEvent event : events) {
if (event instanceof ReplacementEvent) {
ReplacementEvent re = (ReplacementEvent)event;
re.getOriginal().reverse();
} else {
event.reverse();
}
}
}
}