dll类中的C 传统驱动程序mongodb replicaset

C++ Legacy Driver mongoDB Replicaset in Class of a DLL

本文关键字:驱动程序 mongodb replicaset 传统 dll      更新时间:2023-10-16

我已经建立了一个DLL,其中包括实现mongoDB replicaset操作的类。这是班级的摘要。

#include "mongo/client/dbclient.h"
mongoimp::mongoimp() {
    mongo::client::initialize();
}
mongoimp::~mongoimp() {
    mongo::client::shutdown();
}
int mongoimp::queryTRecords() {
    string errmsg;
    vector<mongo::HostAndPort> hosts = { mongo::HostAndPort("xx-a0.yyyy.com:xxxxx"), mongo::HostAndPort("xx-a1.yyyy.com:xxxxx") };
    static mongo::DBClientReplicaSet con("xx", hosts, 0);
    con.connect();
    con.auth("dbname", "username", "password", errmsg);
    auto_ptr<DBClientCursor> cursor = con.query("dbname.t", BSONObj());
    BSONObj response;
    con.logout("xx", response);
    if (cursor->more()) {
        BSONObj recordnm = cursor->nextSafe();
        return(recordnm.getIntField("lastid"));
    } else return(-1);
}

上述代码正在工作。但这是我的问题:

1)使用上述设置,我可以使用DLL进行普通的MongoDB操作发现replicaset实例服务器)更新数据时。

2)只有服务器需要与MongoDB数据库进行对话。因此,基本上我只需要与数据库的一个连接。因此,我想将Mongo :: DBClientReplicaset Con声明为静态全局变量,并在类构造函数中连接到它。但看来我做不到。我的应用程序根本无法运行。这样,我不断收到以下错误。

断言失败:px!= 0,文件c: boost include boost-1_62 boost/smart_ptr/scoped_ptr.hpp,行105

有人知道如何解决问题吗?

以下是我尝试的代码:

static mongo::DBClientReplicaSet con("xx", { mongo::HostAndPort("xx-a0.yyyy.com:xxxxx"), mongo::HostAndPort("xx-a1.yyyy.com:xxxxx") }, 0);
mongoimp::mongoimp() {
    mongo::client::initialize();
    string errmsg;
    con.connect();
    con.auth("dbname", "username", "password", errmsg);
}
mongoimp::~mongoimp() {
    BSONObj response;
    con.logout("xx", response);
    mongo::client::shutdown();
}
int mongoimp::queryTRecords() {
    auto_ptr<DBClientCursor> cursor = con.query("dbname.t", BSONObj());
    if (cursor->more()) {
        BSONObj recordnm = cursor->nextSafe();
        return(recordnm.getIntField("lastid"));
    } else return(-1);
}

3)最后一个问题,我注意到有mongo/client/dbclient_rs.h" for peplicaset。但是我似乎无法使用它。这样,我会遇到initialize()和auto_ptr cursor的错误。使用该文件并充分利用Replicaset功能?如果可以使用" dbclient_rs.h",我该如何初始化Relica集?在这种情况下,我该如何查询和获取数据?

预先感谢!

对于第2号问题,我记得错误的原因:

您需要在构造任何驱动程序对象或为此bson之前调用Mongo :: Client ::初始化。

但是如何使全局定义成为可能,我仍然需要解决方案。