首页 数据库 mysql教程 How to use MongoDB as a pure in-memory DB (Redis s

How to use MongoDB as a pure in-memory DB (Redis s

Jun 07, 2016 pm 04:38 PM
mongodb use

原po The idea There has been a growing interest in using MongoDB as an in-memory database, meaning that the data is not stored on disk at all. This can be super useful for applications like: a write-heavy cache in front of a slower RDBMS s

原po

The idea

There has been a growing interest in using MongoDB as an in-memory database, meaning that the data is not stored on disk at all. This can be super useful for applications like:

  • a write-heavy cache in front of a slower RDBMS system
  • embedded systems
  • PCI compliant systems where no data should be persisted
  • unit testing where the database should be light and easily cleaned

That would be really neat indeed if it was possible: one could leverage the advanced querying / indexing capabilities of MongoDB without hitting the disk. As you probably know the disk IO (especially random) is the system bottleneck in 99% of cases, and if you are writing data you cannot avoid hitting the disk.

One sweet design choice of MongoDB is that it uses memory-mapped files to handle access to data files on disk. This means that MongoDB does not know the difference between RAM and disk, it just accesses bytes at offsets in giant arrays representing files and the OS takes care of the rest! It is this design decision that allows MongoDB to run in RAM with no modification.

How it is done

This is all achieved by using a special type of filesystem called tmpfs. Linux will make it appear as a regular FS but it is entirely located in RAM (unless it is larger than RAM in which case it can swap, which can be useful!). I have 32GB RAM on this server, let’s create a 16GB tmpfs:

<code># mkdir /ramdata
# mount -t tmpfs -o size=16000M tmpfs /ramdata/
# df
Filesystem           1K-blocks      Used Available Use% Mounted on
/dev/xvde1             5905712   4973924    871792  86% /
none                  15344936         0  15344936   0% /dev/shm
tmpfs                 16384000         0  16384000   0% /ramdata</code>
登录后复制

Now let’s start MongoDB with the appropriate settings. smallfiles and noprealloc should be used to reduce the amount of RAM wasted, and will not affect performance since it’s all RAM based. nojournal should be used since it does not make sense to have a journal in this context!

<code>dbpath=/ramdata
nojournal = true
smallFiles = true
noprealloc = true</code>
登录后复制

After starting MongoDB, you will find that it works just fine and the files are as expected in the FS:

<code># mongo
MongoDB shell version: 2.3.2
connecting to: test
> db.test.insert({a:1})
> db.test.find()
{ "_id" : ObjectId("51802115eafa5d80b5d2c145"), "a" : 1 }
# ls -l /ramdata/
total 65684
-rw-------. 1 root root 16777216 Apr 30 15:52 local.0
-rw-------. 1 root root 16777216 Apr 30 15:52 local.ns
-rwxr-xr-x. 1 root root        5 Apr 30 15:52 mongod.lock
-rw-------. 1 root root 16777216 Apr 30 15:52 test.0
-rw-------. 1 root root 16777216 Apr 30 15:52 test.ns
drwxr-xr-x. 2 root root       40 Apr 30 15:52 _tmp</code>
登录后复制

Now let’s add some data and make sure it behaves properly. We will create a 1KB document and add 4 million of them:

<code>> str = ""
> aaa = "aaaaaaaaaa"
aaaaaaaaaa
> for (var i = 0; i  for (var i = 0; i  db.foo.stats()
{
        "ns" : "test.foo",
        "count" : 4000000,
        "size" : 4544000160,
        "avgObjSize" : 1136.00004,
        "storageSize" : 5030768544,
        "numExtents" : 26,
        "nindexes" : 1,
        "lastExtentSize" : 536600560,
        "paddingFactor" : 1,
        "systemFlags" : 1,
        "userFlags" : 0,
        "totalIndexSize" : 129794000,
        "indexSizes" : {
                "_id_" : 129794000
        },
        "ok" : 1
}</code>
登录后复制

The document average size is 1136 bytes and it takes up about 5GB of storage. The index on _id takes about 130MB. Now we need to verify something very important: is the data duplicated in RAM, existing both within MongoDB and the filesystem? Remember that MongoDB does not buffer any data within its own process, instead data is cached in the FS cache. Let’s drop the FS cache and see what is in RAM:

<code># echo 3 > /proc/sys/vm/drop_caches 
# free
             total       used       free     shared    buffers     cached
Mem:      30689876    6292780   24397096          0       1044    5817368
-/+ buffers/cache:     474368   30215508
Swap:            0          0          0</code>
登录后复制

As you can see there is 6.3GB of used RAM of which 5.8GB is in FS cache (buffers). Why is there still 5.8GB of FS cache even after all caches were dropped?? The reason is that Linux is smart and it does not duplicate the pages between tmpfs and its cache… Bingo! That means your data exists with a single copy in RAM. Let’s access all documents and verify RAM usage is unchanged:

<code>> db.foo.find().itcount()
4000000
# free
             total       used       free     shared    buffers     cached
Mem:      30689876    6327988   24361888          0       1324    5818012
-/+ buffers/cache:     508652   30181224
Swap:            0          0          0
# ls -l /ramdata/
total 5808780
-rw-------. 1 root root  16777216 Apr 30 15:52 local.0
-rw-------. 1 root root  16777216 Apr 30 15:52 local.ns
-rwxr-xr-x. 1 root root         5 Apr 30 15:52 mongod.lock
-rw-------. 1 root root  16777216 Apr 30 16:00 test.0
-rw-------. 1 root root  33554432 Apr 30 16:00 test.1
-rw-------. 1 root root 536608768 Apr 30 16:02 test.10
-rw-------. 1 root root 536608768 Apr 30 16:03 test.11
-rw-------. 1 root root 536608768 Apr 30 16:03 test.12
-rw-------. 1 root root 536608768 Apr 30 16:04 test.13
-rw-------. 1 root root 536608768 Apr 30 16:04 test.14
-rw-------. 1 root root  67108864 Apr 30 16:00 test.2
-rw-------. 1 root root 134217728 Apr 30 16:00 test.3
-rw-------. 1 root root 268435456 Apr 30 16:00 test.4
-rw-------. 1 root root 536608768 Apr 30 16:01 test.5
-rw-------. 1 root root 536608768 Apr 30 16:01 test.6
-rw-------. 1 root root 536608768 Apr 30 16:04 test.7
-rw-------. 1 root root 536608768 Apr 30 16:03 test.8
-rw-------. 1 root root 536608768 Apr 30 16:02 test.9
-rw-------. 1 root root  16777216 Apr 30 15:52 test.ns
drwxr-xr-x. 2 root root        40 Apr 30 16:04 _tmp
# df
Filesystem           1K-blocks      Used Available Use% Mounted on
/dev/xvde1             5905712   4973960    871756  86% /
none                  15344936         0  15344936   0% /dev/shm
tmpfs                 16384000   5808780  10575220  36% /ramdata</code>
登录后复制

And that verifies it! :)

What about replication?

You probably want to use replication since a server loses its RAM data upon reboot! Using a standard replica set you will get automatic failover and more read capacity. If a server is rebooted MongoDB will automatically rebuild its data by pulling it from another server in the same replica set (resync). This should be fast enough even in cases with a lot of data and indices since all operations are RAM only :)

It is important to remember that write operations get written to a special collection called oplog which resides in the local database and takes 5% of the volume by default. In my case the oplog would take 5% of 16GB which is 800MB. In doubt, it is safer to choose a fixed oplog size using the oplogSize option. If a secondary server is down for a longer time than the oplog contains, it will have to be resynced. To set it to 1GB, use:

<code>oplogSize = 1000</code>
登录后复制

What about sharding?

Now that you have all the querying capabilities of MongoDB, what if you want to implement a large service with it? Well you can use sharding freely to implement a large scalable in-memory store. Still the config servers (that contain the chunk distribution) should be disk based since their activity is small and rebuilding a cluster from scratch is not fun.

What to watch for

RAM is a scarce resource, and in this case you definitely want the entire data set to fit in RAM. Even though tmpfs can resort to swapping the performance would drop dramatically. To make best use of the RAM you should consider:

  • usePowerOf2Sizes option to normalize the storage buckets
  • run a compact command or resync the node periodically.
  • use a schema design that is fairly normalized (avoid large document growth)

Conclusion

Sweet, you can now use MongoDB and all its features as an in-memory RAM-only store! Its performance should be pretty impressive: during the test with a single thread / core I was achieving 20k writes per second, and it should scale linearly over the number of cores.

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

AI Hentai Generator

AI Hentai Generator

免费生成ai无尽的。

热门文章

R.E.P.O.能量晶体解释及其做什么(黄色晶体)
2 周前 By 尊渡假赌尊渡假赌尊渡假赌
仓库:如何复兴队友
4 周前 By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island冒险:如何获得巨型种子
3 周前 By 尊渡假赌尊渡假赌尊渡假赌

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

mongodb一般用哪个版本 mongodb一般用哪个版本 Apr 07, 2024 pm 05:48 PM

推荐使用 MongoDB 最新版本(当前为 5.0),因为它提供了最新特性和改进。选择版本时,需考虑功能需求、兼容性、稳定性和社区支持,例如:最新版本具有事务、聚合管道优化等特性。确保版本与应用程序兼容。生产环境选择长期支持版本。最新版本有更活跃的社区支持。

nodejs和vuejs区别 nodejs和vuejs区别 Apr 21, 2024 am 04:17 AM

Node.js 是一种服务器端 JavaScript 运行时,而 Vue.js 是一个客户端 JavaScript 框架,用于创建交互式用户界面。Node.js 用于服务器端开发,如后端服务 API 开发和数据处理,而 Vue.js 用于客户端开发,如单页面应用程序和响应式用户界面。

利用MongoDB实现实时推荐系统的经验分享 利用MongoDB实现实时推荐系统的经验分享 Nov 03, 2023 pm 04:37 PM

随着互联网的发展,人们的生活越来越数字化,个性化需求也越来越强烈。在这个信息爆炸的时代,用户往往面对海量的信息无从选择,所以实时推荐系统的重要性愈发凸显出来。本文将分享利用MongoDB实现实时推荐系统的经验,希望能为开发者们提供一些启发和帮助。一、MongoDB简介MongoDB是一个开源的NoSQL数据库,它以高性能、易扩展和灵活的数据模型而闻名。相比传

mongodb创建的数据库在哪里 mongodb创建的数据库在哪里 Apr 07, 2024 pm 05:39 PM

MongoDB 数据库的数据存储在指定的数据目录中,该目录可以位于本地文件系统、网络文件系统或云存储中,具体位置如下:本地文件系统:默认路径为 Linux/macOS:/data/db,Windows:C:\data\db。网络文件系统:路径取决于文件系统。云存储:路径由云存储提供商决定。

mongodb数据库的优势有哪些 mongodb数据库的优势有哪些 Apr 07, 2024 pm 05:21 PM

MongoDB 数据库以其灵活、可扩展和高性能而闻名。它的优势包括:文档数据模型,允许以灵活和非结构化的方式存储数据。水平可扩展性,可通过分片扩展到多个服务器。查询灵活性,支持复杂的查询和聚合操作。数据复制和容错,确保数据的冗余和高可用性。JSON 支持,便于与前端应用程序集成。高性能,即使处理大量数据也能实现快速响应。开源,可定制且免费使用。

mongodb是什么意思 mongodb是什么意思 Apr 07, 2024 pm 05:57 PM

MongoDB是一款面向文档的、分布式数据库系统,用于存储和管理大量结构化和非结构化数据。其核心概念包括文档存储和分布式,主要特性有动态模式、索引、聚集、映射-归约和复制。它广泛应用于内容管理系统、电子商务平台、社交媒体网站、物联网应用和移动应用开发等领域。

mongodb数据库文件在哪 mongodb数据库文件在哪 Apr 07, 2024 pm 05:42 PM

MongoDB 数据库文件位于 MongoDB 数据目录中,默认情况下为 /data/db,其中包含 .bson(文档数据)、ns(集合信息)、journal(写入操作记录)、wiredTiger(使用 WiredTiger 存储引擎时的数据)和 config(数据库配置信息)等文件。

mongodb怎么开启 mongodb怎么开启 Apr 07, 2024 pm 06:15 PM

在 Linux/macOS 上:创建数据目录并启动 "mongod" 服务。在 Windows 上:创建数据目录并从服务管理器中启动 MongoDB 服务。在 Docker 中:运行 "docker run" 命令。在其他平台上:请查阅 MongoDB 文档。验证方式:运行 "mongo" 命令以连接并查看服务器版本。

See all articles