本文主要是介绍c++ 连接 MongoDB replica-set,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
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 setreturn 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:27017
Thu May 9 19:37:56.949 successfully connected to seed d1:27017 for replica set rs1
Thu 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 rs1
Thu May 9 19:37:56.952 successfully connected to new host d1:27017 in replica set rs1
Thu May 9 19:37:56.952 trying to add new host d2:27017 to replica set rs1
Thu May 9 19:37:56.953 successfully connected to new host d2:27017 in replica set rs1
Thu May 9 19:37:56.953 trying to add new host d3:27017 to replica set rs1
Thu May 9 19:37:56.956 successfully connected to new host d3:27017 in replica set rs1
Thu May 9 19:37:56.960 Primary for replica set rs1 changed to d1:27017
Thu May 9 19:37:56.967 replica set monitor for replica set rs1 started, address is rs1/d1:27017,d2:27017,d3:27017
Thu May 9 19:37:56.967 [ReplicaSetMonitorWatcher] starting
上面说明当前连接成功,并且正在使用d1为primary。
测试程序,一切工作正常。
结论是,MongoDB C++的官方文档真恶心,这帮C++程序员也许是天才,但是和规范化相当好的Java社区有老大的距离。只能去看他们的代码和注释才能找到如何使用。
这篇关于c++ 连接 MongoDB replica-set的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!