随笔 - 836  文章 - 1 评论 - 40 阅读 - 102万
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

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   lshan  阅读(357)  评论(0编辑  收藏  举报
编辑推荐:
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
历史上的今天:
2018-08-20 DDD领域驱动设计
2018-08-20 在Ubuntu下如何用CrossOver安装兼容性比较好的QQ(或TIM)
点击右上角即可分享
微信分享提示