데이터 베이스 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 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

net4.0의 용도는 무엇입니까 net4.0의 용도는 무엇입니까 May 10, 2024 am 01:09 AM

.NET 4.0은 다양한 애플리케이션을 만드는 데 사용되며 객체 지향 프로그래밍, 유연성, 강력한 아키텍처, 클라우드 컴퓨팅 통합, 성능 최적화, 광범위한 라이브러리, 보안, 확장성, 데이터 액세스 및 모바일을 포함한 풍부한 기능을 애플리케이션 개발자에게 제공합니다. 개발 지원.

데비안에서 MongoDB 자동 확장을 구성하는 방법 데비안에서 MongoDB 자동 확장을 구성하는 방법 Apr 02, 2025 am 07:36 AM

이 기사는 데비안 시스템에서 MongoDB를 구성하여 자동 확장을 달성하는 방법을 소개합니다. 주요 단계에는 MongoDB 복제 세트 및 디스크 공간 모니터링 설정이 포함됩니다. 1. MongoDB 설치 먼저 MongoDB가 데비안 시스템에 설치되어 있는지 확인하십시오. 다음 명령을 사용하여 설치하십시오. sudoaptupdatesudoaptinstall-imongb-org 2. MongoDB Replica 세트 MongoDB Replica 세트 구성은 자동 용량 확장을 달성하기위한 기초 인 고 가용성 및 데이터 중복성을 보장합니다. MongoDB 서비스 시작 : sudosystemctlstartMongodsudosys

Composer를 사용하여 권장 시스템의 딜레마를 해결하십시오 : Andres-Montanez/권장 사항-펀들 Composer를 사용하여 권장 시스템의 딜레마를 해결하십시오 : Andres-Montanez/권장 사항-펀들 Apr 18, 2025 am 11:48 AM

전자 상거래 웹 사이트를 개발할 때 어려운 문제가 발생했습니다. 사용자에게 개인화 된 제품 권장 사항을 제공하는 방법. 처음에는 간단한 권장 알고리즘을 시도했지만 결과는 이상적이지 않았으며 사용자 만족도에도 영향을 미쳤습니다. 추천 시스템의 정확성과 효율성을 향상시키기 위해보다 전문적인 솔루션을 채택하기로 결정했습니다. 마지막으로 Composer를 통해 Andres-Montanez/Residations-Bundle을 설치하여 문제를 해결했을뿐만 아니라 추천 시스템의 성능을 크게 향상 시켰습니다. 다음 주소를 통해 작곡가를 배울 수 있습니다.

데비안에서 MongoDB의 고 가용성을 보장하는 방법 데비안에서 MongoDB의 고 가용성을 보장하는 방법 Apr 02, 2025 am 07:21 AM

이 기사는 데비안 시스템에서 고도로 사용 가능한 MongoDB 데이터베이스를 구축하는 방법에 대해 설명합니다. 우리는 데이터 보안 및 서비스가 계속 운영되도록하는 여러 가지 방법을 모색 할 것입니다. 주요 전략 : ReplicaSet : ReplicaSet : 복제품을 사용하여 데이터 중복성 및 자동 장애 조치를 달성합니다. 마스터 노드가 실패하면 복제 세트는 서비스의 지속적인 가용성을 보장하기 위해 새 마스터 노드를 자동으로 선택합니다. 데이터 백업 및 복구 : MongoDump 명령을 정기적으로 사용하여 데이터베이스를 백업하고 데이터 손실의 위험을 처리하기 위해 효과적인 복구 전략을 공식화합니다. 모니터링 및 경보 : 모니터링 도구 (예 : Prometheus, Grafana) 배포 MongoDB의 실행 상태를 실시간으로 모니터링하고

MongoDB 데이터베이스 비밀번호를 보는 Navicat의 방법 MongoDB 데이터베이스 비밀번호를 보는 Navicat의 방법 Apr 08, 2025 pm 09:39 PM

해시 값으로 저장되기 때문에 MongoDB 비밀번호를 Navicat을 통해 직접 보는 것은 불가능합니다. 분실 된 비밀번호 검색 방법 : 1. 비밀번호 재설정; 2. 구성 파일 확인 (해시 값이 포함될 수 있음); 3. 코드를 점검하십시오 (암호 하드 코드 메일).

Centos Mongodb 백업 전략은 무엇입니까? Centos Mongodb 백업 전략은 무엇입니까? Apr 14, 2025 pm 04:51 PM

CentOS 시스템 하에서 MongoDB 효율적인 백업 전략에 대한 자세한 설명이 기사는 CentOS 시스템에서 MongoDB 백업을 구현하기위한 다양한 전략을 자세히 소개하여 데이터 보안 및 비즈니스 연속성을 보장 할 것입니다. Docker 컨테이너 환경에서 수동 백업, 시간이 정해진 백업, 자동 스크립트 백업 및 백업 메소드를 다루고 백업 파일 관리를위한 모범 사례를 제공합니다. 수동 백업 : MongoDump 명령을 사용하여 Manual 전체 백업을 수행하십시오 (예 : Mongodump-HlocalHost : 27017-U username-P password-d 데이터베이스 이름 -o/백업 디렉토리이 명령은 지정된 데이터베이스의 데이터 및 메타 데이터를 지정된 백업 디렉토리로 내보내게됩니다.

Centos에서 Gitlab 용 데이터베이스를 선택하는 방법 Centos에서 Gitlab 용 데이터베이스를 선택하는 방법 Apr 14, 2025 pm 04:48 PM

CentOS 시스템의 GitLab 데이터베이스 배포 안내서 올바른 데이터베이스를 선택하는 것은 GitLab을 성공적으로 배포하는 데 중요한 단계입니다. Gitlab은 MySQL, PostgreSQL 및 MongoDB를 포함한 다양한 데이터베이스와 호환됩니다. 이 기사는 이러한 데이터베이스를 선택하고 구성하는 방법을 자세히 설명합니다. 데이터베이스 선택 권장 사항 MySQL : 널리 사용되는 RDBMS (Relational Database Management System). PostgreSQL : 강력한 오픈 소스 RDBM은 복잡한 쿼리 및 고급 기능을 지원하며 대형 데이터 세트를 처리하는 데 적합합니다. MongoDB : 인기있는 NOSQL 데이터베이스, 바다 취급에 능숙합니다

Debian MongoDB에서 데이터를 암호화하는 방법 Debian MongoDB에서 데이터를 암호화하는 방법 Apr 12, 2025 pm 08:03 PM

데비안 시스템에서 MongoDB 데이터베이스를 암호화하려면 다음 단계에 따라 필요합니다. 1 단계 : 먼저 MongoDB 설치 먼저 Debian 시스템이 MongoDB가 설치되어 있는지 확인하십시오. 그렇지 않은 경우 설치를위한 공식 MongoDB 문서를 참조하십시오 : https://docs.mongodb.com/manual/tutorial/install-mongodb-ondodb-on-debian/step 2 : 암호화 키 파일 생성 암호화 키를 포함하는 파일을 만듭니다.

See all articles