1

I'm trying to persit my mongoDB connection like that :

mongo **ptr = (mongo**)get_env(argv, US_VHOST_DATA);

if(!ptr[0]) {
  mongo_replica_set_init( conn, "cluster" );
  mongo_replica_set_add_seed( conn, "mongo1.mongood.com", 27017 );
  mongo_replica_set_add_seed( conn, "mongo3.mongood.com", 27017 );
  mongo_replica_set_add_seed( conn, "mongo4.mongood.com", 27017 );
  mongo_replica_set_add_seed( conn, "mongo5.mongood.com", 27017 );
  mongo_replica_set_add_seed( conn, "mongo6.mongood.com", 27017 );
  mongo_replica_set_client( conn );
  mongo_cmd_authenticate( conn, "dbname", "dbuser", "dbpass" );

  ptr[0] = (mongo*)calloc(1, sizeof(conn));
} else {
  conn[0] = *ptr[0];
}
int count = 0;
count = mongo_count( ptr[0], "dbname", "coll", NULL);

mongo_destroy( ptr[0] );

xbuf_xcat(reply, "<h3>%d</h3>", count);

But obviously, it don't work... My goal is to avoid connection time on each request (~30ms)

It is doable ? What is wrong in this example ?

The code don't complain but it just return -1 instead of the right count number.

Thank you for your help.


[EDIT] Removing the else block and removing the mongo_destroy line just work as expected \o/

Gil
  • 3,279
  • 1
  • 15
  • 25
solisoft
  • 669
  • 4
  • 12
  • I suggest that you rather use a per thread connection by using the __thread keyword: **__thread conn** = 0; and then **if(!conn) { setup(); }** this way you will better use the MongoDB capabilities. – Gil Jan 23 '13 at 13:50
  • There is a sample somewhere? – solisoft Jan 23 '13 at 14:32
  • Look at the mysql.c example provided with the G-WAN download. It does the same job in a way that will not confuse you – Gil Jan 23 '13 at 16:25

2 Answers2

2

I've never used mongo, but looking at your code you are allocating space to ptr[0] but you have not assigned anything to it, so subsequent calls will always return -1. And the else block is doing nothing because you are making all mongo calls using ptr[0] instead of conn, so either remove the else block or correct all the mongo calls to use conn instead of ptr[0] and don't forget to assign conn to ptr after the calloc.

Paulo Melo
  • 176
  • 1
  • 1
  • Yes, I forgot to said that I am not a C developer :) Trying to learn it actually – solisoft Jan 23 '13 at 14:28
  • I just added ptr[0] = conn; below the calloc and removed else block ... but still -1 is returned When calling script for the first time, it return the right number ... then reloading provide a -1 – solisoft Jan 23 '13 at 14:33
0

Look at the mysql.c example provided with the G-WAN download. It does the same job in a way that will not confuse you.

Gil
  • 3,279
  • 1
  • 15
  • 25