在各類系統應用服務端開發中,我們經常會遇到文件存儲的問題。 常見的磁盤文件系統,DBMS傳統文件流存儲。今天我們看一下基于NoSQL數據庫MongoDb的存儲方案。筆者環境 以CentOS 6.5,MongoDb 2.6.3, Nginx-1.4.7 為例,您需要了解linux常用命令。
先來回顧一下MongoDb的內部文件結構
然后是GridFs的結構
GridFS在數據庫中,默認使用fs.chunks和fs.files來存儲文件。
其中fs.files集合存放文件的信息,fs.chunks存放文件數據。
一個fs.files集合中的一條記錄內容如下,即一個file的信息如下:
{ "_id" : ObjectId("4f4608844f9b855c6c35e298"), //唯一id,可以是用戶自定義的類型"filename" : "CPU.txt", //文件名"length" : 778, //文件長度"chunkSize" : 262144, //chunk的大小"uploadDate" : ISODate("2012-02-23T09:36:04.593Z"), //上傳時間"md5" : "e2c789b036cfb3b848ae39a24e795ca6", //文件的md5值"contentType" : "text/plain" //文件的MIME類型"meta" : null //文件的其它信息,默認是沒有”meta”這個key,用戶可以自己定義為任意BSON對象}
對應的fs.chunks中的chunk如下:
{ "_id" : ObjectId("4f4608844f9b855c6c35e299"), //chunk的id"files_id" : ObjectId("4f4608844f9b855c6c35e298"), //文件的id,對應fs.files中的對象,相當于fs.files集合的外鍵"n" : 0, //文件的第幾個chunk塊,如果文件大于chunksize的話,會被分割成多個chunk塊"data" : BinData(0,"QGV...") //文件的二進制數據,這里省略了具體內容}
文件存入到GridFS過程中,如果文件大于chunksize,則把文件分割成多個chunk,再把這些chunk保存到fs.chunks中,最后再把文件信息存入到fs.files中。
在讀取文件的時候,先據查詢的條件,在fs.files中找到一個合適的記錄,得到“_id”的值,再據這個值到fs.chunks中查找所有“files_id”為“_id”的chunk,并按“n”排序,最后依次讀取chunk中“data”對象的內容,還原成原來的文件。
1.安裝mongoDb
增加MongoDB Repository,不清楚vim,請參考VIM
vim /etc/yum.repos.d/mongodb.repo
如果是64bit的
[mongodb]
name=MongoDB Repository
baseurl=http://downloads-distro.mongodb.org/repo/redhat/os/x86_64/
gpgcheck=0
enabled=1
32bit的系統:
[mongodb]
name=MongoDB Repository
baseurl=http://downloads-distro.mongodb.org/repo/redhat/os/i686/
gpgcheck=0
enabled=1
然后安裝,會提示Y/N:
yum install mongo-10gen mongo-10gen-server
啟動:
service mongod start
查看狀態
service mongod status
停止
service mongod stop
更多,關于3.0以上版本,請參考官網。
2.安裝nginx及nginx-gridfs
依賴庫、工具
# yum -y install pcre-devel openssl-devel zlib-devel
# yum -y install gcc gcc-c++
下載nginx-gridfs源碼
# git clone https://github.com/mdirolf/nginx-gridfs.git
# cd nginx-gridfs
# git checkout v0.8
# git submodule init
# git submodule update
下載nginx源碼,編譯安裝。(高版本支持不好)
# wget http://nginx.org/download/nginx-1.4.7.tar.gz
# tar zxvf nginx-1.4.7.tar.gz
# cd nginx-1.4.7
# ./configure --with-openssl=/usr/include/openssl --add-module=../nginx-gridfs/
# make -j8 && make install –j8
注意藍色字符配置成對應nginx-gridfs的路徑
3. 配置nginx-gridfs
vim /usr/local/nginx/conf/nginx.conf
在 server 節點中添加 location 節點
location /img/ {
gridfs testdb
field=filename
type=string;
mongo 192.168.0.159:27017;
}
location /files/ {
gridfs testdb
field=_id
type=objectid;
mongo 192.168.0.159:27017;
}
這里我們的mongo服務在ip 192.168.0.159。
如果不指定 field,默認為 MongoDB 的自增ID,且type為int
配置參數介紹:
gridfs:nginx識別插件的關鍵字
testdb:db名
[root_collection]: 選擇collection,如root_collection=blog, mongod就會去找blog.files與blog.chunks兩個塊,默認是fs
[field]: 查詢字段,保證mongdb里有這個字段名,支持_id, filename, 可省略, 默認是_id
[type]: 解釋field的數據類型,支持objectid, int, string, 可省略, 默認是int
[user]: 用戶名, 可省略
[pass]: 密碼, 可省略
mongo: mongodb url
# /usr/local/nginx/sbin/nginx
可能出現:
Nginx [emerg]: bind() to 0.0.0.0:80 failed (98: Address already in use)
這時可用使用命令關閉占用80端口的程序
sudo fuser -k 80/tcp
用原生的命令行上傳一個文件
mongofiles put 937910.jpg --local ~/937910_100.jpg --host 192.168.0.159 --port 27017 --db testdb --type jpg
937910.jpg是我們提前下載好一個圖片文件,注意我們沒有指定collection,默認是fs
從http://www.robomongo.org/安裝robomongo管理工具, 查看剛剛上傳的文件
最后我們在瀏覽器訪問,如果看到圖片就OK了
http://192.168.0.159/img/937910.jpg
對于.net環境下mongodb CSharpDriver 1.10.0 從Nuget:
Install-Package mongocsharpdriver -Version 1.10.0
我們使用如下片段代碼:
int nFileLen = fileUploadModel.FileBytes.Length; MongoGridFSSettings fsSetting = new MongoGridFSSettings() { Root = CollectionName }; MongoGridFS fs = new MongoGridFS(mongoServer, MongoDatabaseName, fsSetting); //調用Write、WriteByte、WriteLine函數時需要手動設置上傳時間 //通過Metadata 添加附加信息 MongoGridFSCreateOptions option = new MongoGridFSCreateOptions(); option.Id = ObjectId.GenerateNewId(); var currentDate = DateTime.Now; option.UploadDate = currentDate; option.Aliases = alias; BsonDocument doc = new BsonDocument(); //文檔附加信息存儲 if(fileUploadModel.DocExtraInfo!=null&&fileUploadModel.DocExtraInfo.Count>0) { foreach(var obj in fileUploadModel.DocExtraInfo) { if (!doc.Elements.Any(p => p.Name == obj.Key)) { doc.Add(obj.Key, obj.Value); } } } option.Metadata = doc; //創建文件,文件并存儲數據 using (MongoGridFSStream gfs = fs.Create(fileUploadModel.FileName, option)) { gfs.Write(fileUploadModel.FileBytes, 0, nFileLen); gfs.Close(); } log.ErrorFormat("附件標識:{0} 文件名:{1} 上傳成功", alias, fileUploadModel.FileName); return option.Id.ToString();
注意,目前gridfs-ngnix不支持_id類型是GUID的,關于ObjectId參考官網,如下圖:
mongodb產生objectid還有一個更大的優勢,就是mongodb可以通過自身的服務來產生objectid,也可以通過客戶端的驅動程序來產生。
來自官方2.6.10版本 手冊內容
For documents in a MongoDB collection, you should always use GridFS for storing files larger than 16 MB. In some situations, storing large files may be more efficient in a MongoDB database than on a system-level filesystem.
? If your filesystem limits the number of files in a directory, you can use GridFS to store as many files as needed.
? When you want to keep your files and metadata automatically synced and deployed across a number of systems and facilities. When using geographically distributed replica sets MongoDB can distribute files and their metadata automatically to a number of mongod instances and facilities.
? When you want to access information from portions of large files without having to load whole files into memory, you can use GridFS to recall sections of files without reading the entire file into memory.
Do not use GridFS if you need to update the content of the entire file atomically. As an alternative you can store multiple versions of each file and specify the current version of the file in the metadata. You can update the metadata field that indicates “latest” status in an atomic update after uploading the new version of the file, and later remove PRevious versions if needed.
Furthermore, if your files are all smaller the 16 MB BSON Document Size limit, consider storing the file manually within a single document. You may use the BinData data type to store the binary data. See your drivers documentation for details on using BinData.
原理圖
上圖是MongoDB采用Replica Sets模式的同步流程
上面講了分片的標準,下面是具體在分片時的幾種節點角色
MongoDB的32位版本也是不建議被使用的,因為你只能處理2GB大小的數據。還記得第一個限制么?這是MongoDB關于該限制的說明。
讓我感到驚訝的是,很少有人會查詢關于他們將要使用的工具的限制。幸好,MongoDB的開發人員發布了一篇MongoDB所有限制的博客,你可以提前了解相關信息,避免在使用過程中難堪。
盡管已經不建議被使用了,不過MongoDB還是提供了另外一種復制策略,即主從復制。它解決了12個節點限制問題,不過卻產生了新的問題:如果需要改變集群的主節點,那么你必須得手工完成,感到驚訝?看看這個鏈接吧。
MongoDB中數據復制的復制集策略非常棒,很容易配置并且使用起來確實不錯。但如果集群的節點有12個以上,那么你就會遇到問題。MongoDB中的復制集有12個節點的限制,這里是問題的描述,你可以追蹤這個問題看看是否已經被解決了。
Gridfs最適合大文件存儲 ,特別是視頻,音頻,大型圖片超過16MB大小的文件。小型文件也可以存儲,不過需要付出2次查詢代價(metadata與file content) [Tip#18 50 Tips and Tricks for MongoDB Developers]。不要修改存儲文件的內容,而是更新文件元數據如版本,或上傳新版本的文件,刪除老版本的文件。對于大量文件存儲時,需要多個數據節點,復制,數據分片等。別基于nginx訪問圖片文件,瀏覽器沒有緩存。 從互聯網存儲圖片案例來看,圖片大都是jpg, png與縮略圖文件,分存式文件系統(DFS)會是更好的解決方案。
GridFS官方
Building MongoDB applications with Binary Files Using GridFS
如有想了解更多軟件,系統 IT,企業信息化 資訊,請關注我的微信訂閱號:
作者:Petter Liu
出處:http://www.49028c.com/wintersun/
本文版權歸作者和博客園共有,歡迎轉載,但未經作者同意必須保留此段聲明,且在文章頁面明顯位置給出原文連接,否則保留追究法律責任的權利。
該文章也同時發布在我的獨立博客中-Petter Liu Blog。
新聞熱點
疑難解答