0

In this simple program, I want to reconnect to replica set when the primary node crash. But it doesn't work: if the primary node crash, this program will be terminated immediately without any output, and return 141. I don't know why. What is the proper way to reconnect to replica set?

#include <stdio.h>
#include <mongo.h>

int insertVal(mongo *conn, int val) {
    bson op[1];
    bson_init(op);
    bson_append_int(op, "val", val);
    bson_finish(op);

    int status = mongo_insert(conn, "test.vals", op, NULL);

    bson_destroy(op);
    return status;
}

int main()
{
    mongo conn[1];
    mongo_replset_init(conn, "test");
    mongo_replset_add_seed(conn, "localhost", 27017);
    mongo_replset_add_seed(conn, "localhost", 27018);
    mongo_replset_add_seed(conn, "localhost", 27019);
    int status = mongo_replset_connect(conn);
    if (status != MONGO_OK) {
    return 1;
    }

    for (int i = 0; i < 1000 * 1000; ++i) {
        status = insertVal(conn, i);
        if (status != MONGO_OK) {
            printf("%d\n", status);
            --i;
            mongo_reconnect(conn);
        }
    }

    mongo_destroy(conn);
    return 0;
}
Community
  • 1
  • 1
user805627
  • 4,247
  • 6
  • 32
  • 43

1 Answers1

0

You don't need to do DB management operations like mongo_reconnect(conn); by yourself, and it may caused conflict with mongodb.

See Document here. "Mongodb Replica sets feature automated failover. If the primary goes offline or becomes unresponsive and a majority of the original set members can still connect to each other, the set will elect a new primary".

coderLMN
  • 3,076
  • 1
  • 21
  • 26
  • I tried to remove `mongo_reconnect(conn)`, but the problem was no change. – user805627 Dec 23 '12 at 19:22
  • 2
    I think you don't need to check the replica set status at all, for mongodb will take care of itself. – coderLMN Dec 23 '12 at 19:30
  • I agree with Jinzhao. The only thing you might need to handle if you were doing a lot of work is maybe wait a second or two while Mongo re-elects a new primary. Not sure if that's needed, but something to think about. From my experience electing a new primary isn't instant. – ryan1234 Jan 06 '13 at 04:43