【发布时间】:2020-11-12 16:39:10
【问题描述】:
以下示例使用 Axon 通过 Spring 实现事件溯源(和 CQRS)。
https://github.com/dashsaurabh/event-sourcing-cqrs-axon-spring-boot
关于代码的文章:
http://progressivecoder.com/event-sourcing-and-cqrs-with-axon-and-spring-boot-part-2//
在应用程序中:
- JPA 存储库存储实体的实际状态
- 事件存储在单独的 EventStore 中。
我很难理解在示例中,事件是如何存储在 EventStore 中的。在 AccountQueryServiceImpl 中,创建了一个 EventStore 并用于从中读取事件。但是 EventStore 是如何准确填充的呢? (服务类由 REST Endpoint 调用)
关于 JPA 存储库 accountRepository,每当 BaseEvent 发生时,通过使用 AccountQueryEntityManager 中的 save() 方法保存一个新帐户被解雇,但我找不到将某些内容附加到 EventStore 的代码行。
AccountQueryServiceimpl
@Service
public class AccountQueryServiceImpl implements AccountQueryService {
private final EventStore eventStore;
private final AccountRepository accountRepository;
public AccountQueryServiceImpl(EventStore eventStore, AccountRepository
accountRepository) {
this.eventStore = eventStore;
this.accountRepository = accountRepository;
}
@Override
public List<Object> listEventsForAccount(String accountNumber) {
return eventStore.readEvents(accountNumber).asStream().map( s ->
s.getPayload()).collect(Collectors.toList());
}
@Override
public AccountQueryEntity getAccount(String accountNumber) {
return accountRepository.findById(accountNumber).get();
}
}
AccountQueryEntityManager
@Component
public class AccountQueryEntityManager {
@Autowired
private AccountRepository accountRepository;
@Autowired
@Qualifier("accountAggregateEventSourcingRepository")
private EventSourcingRepository<AccountAggregate> accountAggregateEventSourcingRepository;
@EventSourcingHandler
void on(BaseEvent event){
persistAccount(buildQueryAccount(getAccountFromEvent(event)));
}
private AccountAggregate getAccountFromEvent(BaseEvent event){
return accountAggregateEventSourcingRepository.load(event.id.toString()).getWrappedAggregate().getAggregateRoot();
}
private AccountQueryEntity findExistingOrCreateQueryAccount(String id){
return accountRepository.findById(id).isPresent() ? accountRepository.findById(id).get() : new AccountQueryEntity();
}
private AccountQueryEntity buildQueryAccount(AccountAggregate accountAggregate){
AccountQueryEntity accountQueryEntity = findExistingOrCreateQueryAccount(accountAggregate.getId());
accountQueryEntity.setId(accountAggregate.getId());
accountQueryEntity.setAccountBalance(accountAggregate.getAccountBalance());
accountQueryEntity.setCurrency(accountAggregate.getCurrency());
accountQueryEntity.setStatus(accountAggregate.getStatus());
return accountQueryEntity;
}
private void persistAccount(AccountQueryEntity accountQueryEntity){
accountRepository.save(accountQueryEntity);
}
}
【问题讨论】:
-
请不要通过指向外部来源的链接提供您问题的主要部分。将您有疑问的代码放在您的问题中,并正确格式化为代码。如果这样做工作量太大或涉及太多代码,那么您的问题可能太宽泛了。您需要提供一些简明扼要的内容,让读者无需离开并研究 GitHub 上的项目即可提出问题。
-
谢谢,我会的。