一 安装驱动
yum install mongo-c-driver
#安装json库
yum install libbson
#安装必要得构建和依赖库 连接需要openssl
yum install cmake openssl-devel cyrus-sasl-devel
这样安装后,并没找到头文件,只能重新下载安装,安装还挺麻烦。
- 下载mongo-c-driver驱动:
git clone https://github.com/mongodb/mongo-c-driver.git
本来可以通过cmake .
就可以编译安装了,但是cmake的版本低,只能重新下载。
- 下载cmake和安装cmake
https://cmake.org/files/v3.19/cmake-3.19.2.tar.gz
下载完成后,通过以下步骤安装:
cd cmake-3.19.2
./configure && make && make install
二 多线程
/* gcc example-pool.c -o example-pool $(pkg-config --cflags --libs
* libmongoc-1.0) */
/* ./example-pool [CONNECTION_STRING] */
#include <mongoc/mongoc.h>
#include <pthread.h>
#include <stdio.h>
static pthread_mutex_t mutex;
static bool in_shutdown = false;
static void *
worker (void *data)
{
mongoc_client_pool_t *pool = data;
mongoc_client_t *client;
bson_t ping = BSON_INITIALIZER;
bson_error_t error;
bool r;
BSON_APPEND_INT32 (&ping, "ping", 1);
while (true) {
client = mongoc_client_pool_pop (pool);
/* Do something with client. If you are writing an HTTP server, you
* probably only want to hold onto the client for the portion of the
* request performing database queries.
*/
r = mongoc_client_command_simple (
client, "admin", &ping, NULL, NULL, &error);
if (!r) {
fprintf (stderr, "%s\n", error.message);
}
mongoc_client_pool_push (pool, client);
pthread_mutex_lock (&mutex);
if (in_shutdown || !r) {
pthread_mutex_unlock (&mutex);
break;
}
pthread_mutex_unlock (&mutex);
}
bson_destroy (&ping);
return NULL;
}
int
main (int argc, char *argv[])
{
const char *uri_string = "mongodb://127.0.0.1/?appname=pool-example";
mongoc_uri_t *uri;
bson_error_t error;
mongoc_client_pool_t *pool;
pthread_t threads[10];
unsigned i;
void *ret;
pthread_mutex_init (&mutex, NULL);
mongoc_init ();
if (argc > 1) {
uri_string = argv[1];
}
uri = mongoc_uri_new_with_error (uri_string, &error);
if (!uri) {
fprintf (stderr,
"failed to parse URI: %s\n"
"error message: %s\n",
uri_string,
error.message);
return EXIT_FAILURE;
}
pool = mongoc_client_pool_new (uri);
mongoc_client_pool_set_error_api (pool, 2);
for (i = 0; i < 10; i++) {
pthread_create (&threads[i], NULL, worker, pool);
}
sleep (10);
pthread_mutex_lock (&mutex);
in_shutdown = true;
pthread_mutex_unlock (&mutex);
for (i = 0; i < 10; i++) {
pthread_join (threads[i], &ret);
}
mongoc_client_pool_destroy (pool);
mongoc_uri_destroy (uri);
mongoc_cleanup ();
return EXIT_SUCCESS;
}
三 参考
[https://www.cnblogs.com/oloroso/p/5733083.html](https://www.cnblogs.com/oloroso/p/5733083.html)
[https://www.cnblogs.com/oloroso/p/5740431.html](https://www.cnblogs.com/oloroso/p/5740431.html)
[http://mongoc.org/libmongoc/current/index.html](http://mongoc.org/libmongoc/current/index.html)
[https://blog.csdn.net/farrellcn/article/details/18535991](https://blog.csdn.net/farrellcn/article/details/18535991)
[https://www.cnblogs.com/mophee/archive/2013/03/19/2969456.html](https://www.cnblogs.com/mophee/archive/2013/03/19/2969456.html)
网友评论