MongoDB事件存储引擎

MongoDB是一个基于文档的NoSQL存储。 其可扩展性使其适合用作Event Store。

Axon提供了MongoEventStorageEngine,它使用MongoDB作为后台数据库。 它包含在Axon Mongo模块(Maven artifactId axon-mongo)中。

事件存储在两个独立的集合(collections)中:一个用于实际事件流,另一个用于快照。

默认情况下,MongoEventStorageEngine将每个事件存储在单独的文档中。

但是,可以通过过StorageStrategy来修改。

Axon提供的替代方案是DocumentPerCommitStorageStrategy,它为已经存储在单个提交中(即在同一个DomainEventStream中)的所有事件创建单个文档。

将所有Event 文档中存储的

优点:

1. 该提交以原子方式保存的, 适合复杂的业务场景操作事件

2.任何数量的事件,它只需要一次往返。

缺点

1. 直接在数据库中查询事件变得更加困难。

2. 不适合批量操作的大批量数据集合,对于一些非影响业务的Event 不需要记录.

 

所以开发过程中要根据实际的业务需求,灵活的实现事件的持久化 .

 

Event Store Utilities

Axon提供了许多在某些情况下可能有用的事件存储引擎。

1.将多个事件存储到一起

SequenceEventStorageEngine是两个事件存储引擎的包装。在查询的时候,它会从两个事件存储引擎中返回事件。新增的事件会交给第二个事件存储引擎。例如,在出于性能原因使用两种不同的事件存储实现的情况下,这个效果是非常的明显。第一个是比较大但查询很慢的事件存储库,第二个为快速读取和写入而优化。

 

2.过滤存储事件

FilteringEventStorageEngine允许事件根据谓词(predicate)进行过滤。

只有符合此谓词的事件才会被存储。 注意,使用事件存储作为事件源的事件处理程序可能无法接收这些事件,因为它们未被存储。

If you want to load the event from the mongoDB , you need to store the event . 'If your application not need it , you can filter it as below .'

@Configuration
public class AxonConfig {

    @Value("${spring.data.mongodb.database}")
    private String mongoDbName;
    @Autowired
    private MongoProperties mongoProperties;
    @Autowired
    private Environment env;
    private Predicate<EventMessage<?>> filter;
    @Qualifier("eventSerializer")
    @Bean
     public Serializer axonJsonSerializer() {
        return new JacksonSerializer();
    } 
    @Bean
    public EventStorageEngine eventStorageEngine(){

//String regexEvent=".*RetrySubLzdEvent*.|.*LzdValidatedEvent*.|.*LzdMilestonePushFailedEvent*.|.*LzdMilestonePushSucceedEvent*.|";
       String regexEvent=".*PricingCalculatedEvent.*|.*otherEvent.*";
        filter = m -> !m.getPayloadType().toString().matches(regexEvent);   //This meaning not store those events to mongoDB

        return new FilteringEventStorageEngine(new MongoEventStorageEngine(axonJsonSerializer(), null,
                axonMongoTemplate(), new DocumentPerEventStorageStrategy()),filter);
        
    }

3.内存存储引擎

这里有一个EventStorageEngine的实现。它将存储的事件保存在内存中,他就是InMemoryEventStorageEngine类。

它对于需要将事件存储的短期(short-lived)工具或测试来说就非常有用。
posted on 2019-08-20 15:17  lshan  阅读(347)  评论(0编辑  收藏  举报