大家好!
之前由于公司数据的存储由SQL Server 转向了 MongoDB,所以就对MongoDB很感兴趣,主要是MongoDB的性能方面。性能方面肯定离不开存储引擎, 从 MongoDB 3.2 版本开始Wiredtiger 就是默认的存储引擎了,Wiredtiger比MMAPv1应该快很多,大家可以自己在网上搜索下性能的测试对比。WiredTiger为了适应现代CPU、内存和磁盘的特性而设计的存储引擎,它的特点就是充分利用CPU的速度和内存的容量来弥补磁盘访问速度不足。
在MongoDB的架构上,这些存储引擎都是Plug-in的,即很方便的扩展其他的存储引擎。 所以我就很关心MongoDB是如何跟Wiredtiger存储引擎集成的,然后就阅读了MongDB的源码,有一些收获。 本篇文章就先分享下Mongod(Daemon) 启动阶段做了哪些主要的事情去加载Wiredtiger存储引擎以及如何建立处理外部请求的机制。
首先,先上一张图(图片内容比较多,所以字体看起来有点小,大家放大点看吧)
![6ee50d6c68b5f965740d0bdf372cefe6.png](https://img-blog.csdnimg.cn/img_convert/6ee50d6c68b5f965740d0bdf372cefe6.png)
MongoDB WiredTiger
上图就是Mongod(Daemon) 程序的启动图,大家可以从github(https://github.com/mongodb/mongo)上下载源码对照着看。
- 在MongoDB编译阶段就会做一些设置,注册wiredtigher引擎。At the compiling time, register An construct action function that will attach WiredTigerFactory to service context, and at runtime mongo::runGlobalInitializers will guarantee that the registered construct action function can be executed when service context is initialized. Later ServiceContext::make() will create a singleton serviceContext and execute the registered construction action function.
- 启动mongod.exe(以windows为例), 一般的命令行是.mongod.exe -dbpath=C:myDataplaygroundmongodb,刚开始阶段就会创建serviceContext,以及setUpCatalog(注册DatabaseHolderImpl,IndexAccessMethodFactoryImpl以及CollectionImpl::FactoryImpl到serviceContext).
- 设置Mongod(Daemon)程序的service 入口,ServiceEntryPointMongod Class是Mongod程序对外提供服务的入口。比如mongo shell, 第三方sdk的连接都是通过这个 ServiceEntryPointMongod 入口连接到MongoDB的,默认对外提供服务端口为27017. 外部请求其实是通过TransportLayerASIO class 转入到ServiceEntryPointMongod class的,所以ServiceEntryPointMongod 也需要设置下TransportLayerASIO, 它提供adaptive和synchronous两种服务方式。
- 根据程序启动的配置初始化storege engine。One of thing do here is to read dbpah’s storage.bson to load the engine type, check whether current Mongo support user-specified engine or not, otherwise if not specify engine type when start, set the storage.bson engine type to active engine. 下图中的factory如果启动的时候是使用的wiredtiger engine, 那么这个factory其实就是第一步讲的编译阶段注册的WiredTigerFactory, create方法会创建WiredTigerKVEngine,至此wiredtigher 引擎加载成功。
![2df90294afe518873fa9cded14a27c1b.png](https://img-blog.csdnimg.cn/img_convert/2df90294afe518873fa9cded14a27c1b.png)
5. Start ServiceEntryPointMongod和TransportLayerASIO。TransportLayerASIO start完成后会setup ingress async listener on port 27017。每一个外部的连接请求会启动一个新的session, 并且创建一个ServiceStateMachine来管理这个session的状态,通过ServiceEntryPointMongod的handleRequest方法来处理请求并返回结果。
至此,wiretigher引擎就加载好了,处理外部请求的机制也建立好了, 后续就是根据外部请求进行相应的数据操作。
以上就是Mongod 启动阶段的加载wiredtigher引擎和建议处理外部请求的机制的一些讲解,如果大家感兴趣的话可以留言,后续也可以讲一下数据操作过程中的一些认识。 谢谢大家,有不足的地方请指正!!