MongoDB安装及示例代码

1.下载MongoDB

wget https://fastdl.mongodb.org/linux/mongodb-linux-x86_64-ubuntu1604-4.2.6.tgz

 

2.解压.压缩包

tar -zxvf mongodb-linux-x86_64-ubuntu1604-4.2.6.tgz

 

3.将解压包拷贝到指定目录

mv  mongodb-linux-x86_64-ubuntu1604-4.2.6 /opt/mongodb

 

创建数据库文件夹(默认的数据库文件的位置是/data/db,启动时会自动创建)

 

提示:mongodb没有具体的安装过程,解压文件包后,可以直接使用,非常高效和方便。

touch /opt/mongodb/logs

 

创建文件夹或文件

sudo mkdir -p /data/db    创建目录

sudo mkdir -p /opt/mongodb/logs    创建目录

sudo touch /opt/mongodb/logs/mongodb.log      创建空文件! 注意不是目录而是文件

 

在mongodb安装位置/bin目录 sudo vim mongodb.conf

#数据文件存放目录

dbpath=/data/db

#日志文件存放目录

logpath=/opt/mongodb/logs/mongodb.log

#以守护程序的方式启用,即在后台运行

fork=true

#远程连接

bind_ip=0.0.0.0

 

 

启动服务端

运行mongod命令  sudo /opt/mongodb/bin/mongod

后台启动mongodb  sudo /opt/mongodb/bin/mongod --config /opt/mongodb/bin/mongodb.conf

 

启动客户端

运行mongo命令  sudo /opt/mongodb/bin/mongo

 

代码

#include <mongoc.h>
#include <bson.h>
#include "http_util.h"


void test1(mongoc_collection_t *collection) {
    char json[4096] = {0};
    strcat(json, "{\"name\":\"milomilomilomilomilomilomilomilomilomilomilomilomilomilomilomilomilomilomilomilomilomilomilomilomilomilomilomilomilomilomilomilomilomilomilomilo\"}");

    bson_error_t error;
    bson_t *bson;
    char *string;

    bson = bson_new_from_json((const uint8_t *)json, -1, &error);
    if (!bson) {
        printf("error\n");
    }

    for (int i=0; i<100000; i++) {
        bool r = mongoc_collection_insert(collection, MONGOC_INSERT_NONE, bson, NULL, &error);
        if (!r) {
            printf("insert failure %s\n", error.message);
        }
    }

    bson_destroy(bson);
}

//保存定位数据
void saveLocationData(mongoc_collection_t *collection) {
    //获取定位数据,JOSN
    char json[4096] = {0};
    http_request(json);
    printf("%s\n", json);

    bson_error_t error;
    bson_t *bson;
    char *string;

    bson = bson_new_from_json((const uint8_t *)json, -1, &error);
    if (!bson) {
        printf("error\n");
    }

    //for (int i=0; i<100000; i++) {
        bool r = mongoc_collection_insert(collection, MONGOC_INSERT_NONE, bson, NULL, &error);
        if (!r) {
            printf("insert failure %s\n", error.message);
        }
    //}

    bson_destroy(bson);
}


int main(int argc, char *argv[]) {
    mongoc_collection_t *collection;
    mongoc_database_t *database;
    mongoc_client_t *client;

    mongoc_init();

    client = mongoc_client_new("mongodb://localhost:27017");
    if (client == NULL) {
        printf("error\n");
        return -1;
    }

    collection = mongoc_client_get_collection(client, "lingsheng", "teacher");

    saveLocationData(collection);

    mongoc_collection_destroy(collection);
    mongoc_client_destroy(client);
    mongoc_cleanup();

    return 0;
}

 

http_util.h

 

#include <stdio.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <time.h>
#include <errno.h>
#include <signal.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/time.h>
#include <netinet/in.h>
#include <arpa/inet.h>


typedef enum HTTP_REQUEST_METHOD
{
    GET = 1,
    POST,
    PUT,
    DELETE
} REQUEST_METHOD;

typedef struct HTTP_REQUEST
{
    char *method_type;
    char *request_string;
    char *domain;
    char *params_str;
    char *ip;
    char *route;
    char *content_type;
    char *content_length;
    char *attach_content;
} REQUEST; 

typedef struct HTTP_RESPONSE
{
    char *response_string;
} RESPONSE;

typedef struct HTTP_SOCKET
{
    int sockfd;
    struct sockaddr_in servaddr;
    fd_set t_set;
    struct timeval  tv;
} SOCKET;

void request_head(REQUEST *request);

void get_method(REQUEST *request, char *buf);

void request_action(SOCKET *socket_in, REQUEST_METHOD method);

int response_action(SOCKET *socket_in, RESPONSE *response);

void http_request(char *buf);

http_util.c

#include "http_util.h"

#include <stdio.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <time.h>
#include <errno.h>
#include <signal.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/time.h>
#include <netinet/in.h>
#include <arpa/inet.h>
 
#define IPSTR "106.11.19.8"
#define PORT 80
#define BUFSIZE 2048

void request_head(REQUEST *request) {
    char url[1024];
    memset(url, 0, 1024);

    strcat(url, request->route);
    strcat(url, "?");
    strcat(url, request->params_str);

    strcat(request->request_string, request->method_type);
    strcat(request->request_string, url);
    strcat(request->request_string, " HTTP/1.1\n");
    
    strcat(request->request_string, "Host: ");
    strcat(request->request_string, request->ip);
    strcat(request->request_string, "\n");

    strcat(request->request_string, "Content-Type: ");
    strcat(request->request_string, request->content_type);
    strcat(request->request_string, "\n");

    strcat(request->request_string, "Content-Length: ");
    strcat(request->request_string, request->content_length);
    strcat(request->request_string, "\n\n");

    strcat(request->request_string, request->attach_content);
    strcat(request->request_string, "\r\n\r\n");
    printf("%s\n", request->request_string);
}

void get_method(REQUEST *request, char *buf) {
    request->request_string=(char *)malloc(2048);
    request->method_type=(char *)malloc(16);
    request->route=(char *)malloc(128);
    request->domain=(char *)malloc(128);
    request->params_str=(char *)malloc(512);
    request->ip=(char *)malloc(32);
    request->content_type=(char *)malloc(64);
    request->content_length=(char *)malloc(8);
    request->attach_content=(char *)malloc(256);

    memset(request->request_string, 0, 2048);
    memset(request->method_type, 0, 16);
    memset(request->domain, 0, 128);
    memset(request->params_str, 0, 512);
    memset(request->ip, 0, 32);
    memset(request->content_type, 0, 64);
    memset(request->route, 0, 128);
    memset(request->content_length, 0, 8);
    memset(request->attach_content, 0, 256);

    //restapi.amap.com/v3/geocode/regeo?key=4d607f1ae9841d414e27f8caa0c2e55a&location=112.897992,28.217434&poitype=商务写字楼&radius=1000&extensions=base&batch=false&roadlevel=0
    sprintf(request->domain, "%s", "lbs.amap.com");
    sprintf(request->method_type, "%s", "GET ");
    sprintf(request->ip, "%s", IPSTR);
    sprintf(request->route, "%s", "/v3/geocode/regeo");
    //sprintf(request->params_str, "%s", "location=112.897992,28.217434&key=4d607f1ae9841d414e27f8caa0c2e55a&radius=1000&extensions=all");
    sprintf(request->params_str, "%s", "key=4d607f1ae9841d414e27f8caa0c2e55a&location=112.897992,28.217434&poitype=商务写字楼&radius=1000&extensions=base&batch=false&roadlevel=0");
    sprintf(request->content_type, "%s", "application/x-www-form-urlencoded");

    sprintf(request->attach_content, "%s", "lingsheng");
    socklen_t len = strlen(request->attach_content);
    sprintf(request->content_length, "%d", len);

    request_head(request);

    sprintf(buf, "%s", request->request_string);

    free(request->request_string);
    free(request->domain);
    free(request->params_str);
    free(request->ip);
    free(request->content_type);
}

void request_action(SOCKET *socket_in, REQUEST_METHOD method) {
    bzero(&(socket_in->servaddr), sizeof(socket_in->servaddr));
    socket_in->servaddr.sin_family = AF_INET;
    socket_in->servaddr.sin_port = htons(PORT);
    //将点分十进制的ip地址转化为用于网络传输的数值格式
    //返回值:若成功则为1,若输入不是有效的表达式则为0,若出错则为-1
    if (inet_pton(AF_INET, IPSTR, &(socket_in->servaddr.sin_addr)) <= 0 ){
        printf("创建网络连接失败,本线程即将终止--inet_pton error!\n");
        exit(0);
    };

    if (connect(socket_in->sockfd, (struct sockaddr *)&(socket_in->servaddr), sizeof(socket_in->servaddr)) < 0){
        printf("连接到服务器失败,connect error!\n");
        exit(0);
    }
    printf("与远端建立了连接\n");

    REQUEST request;
    char buf[BUFSIZE];
    memset(buf, 0, BUFSIZE);

    switch (method) {
        case  GET:
            get_method(&request, buf);
        break;
        case  POST:
            printf("POST");
        break;
        case  PUT:
            printf("PUT");
        break;
        case  DELETE:
            printf("DELETE");
        break;
    }

    int ret = write(socket_in->sockfd,buf,strlen(buf));
    if (ret < 0) {
        printf("发送失败!错误代码是%d,错误信息是'%s'\n", errno, strerror(errno));
        exit(0);
    } else {
        printf("消息发送成功,共发送了%d个字节!\n\n", ret);
    }
}

int response_action(SOCKET *socket_in, RESPONSE *response) {
    int h, i;
    FD_ZERO(&(socket_in->t_set));
    FD_SET(socket_in->sockfd, &(socket_in->t_set));

    char buf[1024];
    while (1) {
        sleep(1);
        socket_in->tv.tv_sec= 0;
        socket_in->tv.tv_usec= 0;
        h = 0;
        printf("--------------->1\n");
        h= select(socket_in->sockfd +1, &(socket_in->t_set), NULL, NULL, &(socket_in->tv));
        printf("--------------->2\n");

        //if (h == 0) continue;
        if (h < 0) {
            //close(socket_in->sockfd);
            printf("在读取数据报文时SELECT检测到异常,该异常导致线程终止!\n");
            return -1;
        };

        if (h > 0){
            memset(buf, 0, 1024);
            i= read(socket_in->sockfd, buf, 1023);
            if (i==0){
                //close(socket_in->sockfd);
                printf("读取数据报文时发现远端关闭,该线程终止!\n");
                return -2;
            }

            strcat(response->response_string, buf);
            printf("%s\n", buf);
        }
    }

    return 0;
}


void http_request(char *json) {
    SOCKET socket_in;

    RESPONSE response;
    response.response_string=(char *)malloc(4096);
    memset(response.response_string, 0, 4096);
    if ((socket_in.sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0 ) {
        printf("创建网络连接失败,本线程即将终止---socket error!\n");
        exit(0);
    };

    request_action(&socket_in, GET);

    int ret = response_action(&socket_in, &response);
    if (ret != 0) {
        printf("\n");
    }

    close(socket_in.sockfd);
    
    printf("\n");

    //截取json位置
    char *p;
    p = strchr(response.response_string, '{');
    int pos = p-response.response_string;
    printf("%d\n", pos);

    strncpy(json, response.response_string+pos, strlen(response.response_string));

    printf("\n");
    //printf("%s\n", json);
    printf("\n");

    free(response.response_string);
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值