c++ 串連 MongoDB replica-set

來源:互聯網
上載者:User

MongoDB的官方文檔描述了如何使用連接字串的正確格式來支援single server和replica-set server,並且聲稱官方驅動都支援。

http://docs.mongodb.org/manual/reference/connection-string/

但實際上c++驅動仍然沿用舊的方式,而且文檔描述相當少。可以通過這個討論讓大家看到MongoDB c++驅動有多討厭。

http://stackoverflow.com/questions/14629281/c-driver-mongodb-connection-options

我使用的是MongoDB 2.4.1的C++驅動,通過檢查原始碼,找到了使用的方法。

在mongo-cxx-driver-v2.4.1/src/mongo/client/dbclientinterface.h檔案中,在ConnectionString類頭部有注釋,很奇怪,官方網站的文檔中也能看到,不過沒有換行,看起來特別噁心。http://api.mongodb.org/cplusplus/2.4.3/classmongo_1_1_connection_string.html#details

    /**     * ConnectionString handles parsing different ways to connect to mongo and determining method     * samples:     *    server     *    server:port     *    foo/server:port,server:port   SET     *    server,server,server          SYNC     *                                    Warning - you usually don't want "SYNC", it's used      *                                    for some special things such as sharding config servers.     *                                    See syncclusterconnection.h for more info.     *     * tyipcal use     * string errmsg,     * ConnectionString cs = ConnectionString::parse( url , errmsg );     * if ( ! cs.isValid() ) throw "bad: " + errmsg;     * DBClientBase * conn = cs.connect( errmsg );     */    class ConnectionString {    public:        enum ConnectionType { INVALID , MASTER , PAIR , SET , SYNC, CUSTOM };        ConnectionString() {            _type = INVALID;        }

這裡SET就是指Replica-Set,用法是通過ConnctionString::parse解析字串。

那麼ConnectionString::parse的原始碼呢?在dbclient.cpp檔案中:

    ConnectionString ConnectionString::parse( const string& host , string& errmsg ) {        string::size_type i = host.find( '/' );        if ( i != string::npos && i != 0) {            // replica set            return ConnectionString( SET , host.substr( i + 1 ) , host.substr( 0 , i ) );        }        int numCommas = str::count( host , ',' );        if( numCommas == 0 )            return ConnectionString( HostAndPort( host ) );        if ( numCommas == 1 )            return ConnectionString( PAIR , host );        if ( numCommas == 2 )            return ConnectionString( SYNC , host );        errmsg = (string)"invalid hostname [" + host + "]";        return ConnectionString(); // INVALID    }

也就是先找第一個斜線,然後前面的作為replica-set名稱,後面的用,分割開作為主機名稱。

我需要一種通過配置就能自如的從single server到replica-set切換的方式,這很簡單,因為唯一的變動僅僅是設定檔中的字串。

現在先看一下single server的情況,我有配置如下:

"uri" : "localhost:27017"

然後建立一個自己的mongo_session對象。

shared_ptr<mongo_session> mongo_session_factory::get_session() {    configuration& config = app_singleton_holder::Instance().config();    string error_message;    mongo::ConnectionString host = mongo::ConnectionString::parse(config.mongo_uri, error_message);    if (!host.isValid()) {      throw "bad: " + error_message;    }    shared_ptr<mongo_session> s(new mongo_session(host));    return s;}

我的mongo_session類以前部落格中提過,這裡修改了一點,看一下.h檔案:

#ifndef _MONGO_SESSION_H#define _MONGO_SESSION_H#include <string>#include <mongo/client/connpool.h>class mongo_session { public:    /**     * construct ScopedDBConnection instance and keep it as member variable     */    mongo_session(mongo::ConnectionString const& host, double socketTimeout=0);    /**     * release connction back to pool     */    ~mongo_session();        /**     * Get one connection from pool     */    mongo::DBClientBase& get(); private:    std::auto_ptr<mongo::ScopedDbConnection> con_;};#endif

在看一下.cpp檔案:

#include "helper/mongo_session.h"using namespace mongo;mongo_session::mongo_session(mongo::ConnectionString const& host, double socketTimeout):  con_(mongo::ScopedDbConnection::getScopedDbConnection(host, socketTimeout)) {    }mongo_session::~mongo_session(){  con_->done();}DBClientBase& mongo_session::get(){  return con_->conn();}

測試一下,能夠正常的串連single server。

現在修改一下配置:

"uri" : "rs1/d1:27017,d2:27017,d3:27017"

rs1是我的replica-set名稱

d1, d2,和d3是三個mongodb instances所在的主機名稱。

27017是連接埠號碼。

啟動後,看到終端顯示資訊:

Thu May  9 19:37:56.947 starting new replica set monitor for replica set rs1 with seed of d1:27017,d2:27017,d3:27017Thu May  9 19:37:56.949 successfully connected to seed d1:27017 for replica set rs1Thu May  9 19:37:56.950 changing hosts to { 0: "d1:27017", 1: "d3:27017", 2: "d2:27017" } from rs1/Thu May  9 19:37:56.950 trying to add new host d1:27017 to replica set rs1Thu May  9 19:37:56.952 successfully connected to new host d1:27017 in replica set rs1Thu May  9 19:37:56.952 trying to add new host d2:27017 to replica set rs1Thu May  9 19:37:56.953 successfully connected to new host d2:27017 in replica set rs1Thu May  9 19:37:56.953 trying to add new host d3:27017 to replica set rs1Thu May  9 19:37:56.956 successfully connected to new host d3:27017 in replica set rs1Thu May  9 19:37:56.960 Primary for replica set rs1 changed to d1:27017Thu May  9 19:37:56.967 replica set monitor for replica set rs1 started, address is rs1/d1:27017,d2:27017,d3:27017Thu May  9 19:37:56.967 [ReplicaSetMonitorWatcher] starting

上面說明當前串連成功,並且正在使用d1為primary。

測試程式,一切工作正常。

結論是,MongoDB C++的官方文檔真噁心,這幫C++程式員也許是天才,但是和正常化相當好的Java社區有老大的距離。只能去看他們的代碼和注釋才能找到如何使用。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.