文档首页 > > 快速入门> 集群快速入门> 步骤三:连接集群实例> 程序代码连接集群实例(社区增强版)

程序代码连接集群实例(社区增强版)

分享
更新时间: 2019/10/18 GMT+08:00

本文介绍了通过Python、Java、以及C程序连接实例的方法。

Python程序连接实例

  1. 安装Python 2.7。

    华为云弹性云服务器如果没有安装Python 2.7,请执行如下命令自行安装:

    wget https://www.python.org/ftp/python/2.7.15/Python-2.7.15.tgz

    tar -xvf Python-2.7.15.tgz

    ./configure

    make && make install

  2. 安装pip 18.1。

    华为云弹性云服务器默认没有pip 18.1,请执行如下命令自行安装:

    wget https://bootstrap.pypa.io/get-pip.py -o get-pip.py

    python get-pip.py.1

    wget https://files.pythonhosted.org/packages/45/ae/8a0ad77defb7cc903f09e551d88b443304a9bd6e6f124e75c0fbbf6de8f7/pip-18.1.tar.gz

    tar -zxvf pip-18.1.tar.gz

    cd pip-18.1

    python setup.py install

  3. 安装PyMongo 3.5.1。

    通过pip安装PyMongo 3.5.1:

    python -m pip install pymongo==3.5.1

  4. Python程序连接实例的示例代码:
    #!/usr/bin/python
    from pymongo import MongoClient
    from pymongo.errors import ConnectionFailure
    ##可以复制增强版实例基本信息页面提供的连接信息
    ##例如 mongodb://rwuser:****@10.10.10.10:8635,10.10.10.11:8635/test?authSource=admin
    uri = "mongodb://rwuser:****@10.10.10.10:8635,10.10.10.11:8635/test?authSource=admin"
    client = MongoClient(uri)
    try:
        client.admin.command('ismaster')
    except ConnectionFaiture:
        print 'Connect Failure'
    db = client.test
    doc = {"a":1,"b":1,"c":1}
    doc_id = db.tab.insert(doc)
    print 'doc_id:',doc_id
    for d in db.tab.find():
        print d

Java程序连接实例

  1. 准备java驱动“mongodb-java-driver-3.5.0.jar”,具体请参见MongoDB官方文档

    maven配置:

    <dependencies>
    <dependency>
        <groupId>org.mongodb</groupId>
        <artifactId>mongodb-driver</artifactId>
        <version>3.5.0</version>
    </dependency>
    </dependencies>
  2. 手动编译:
    1. 下载并安装gradle 3.5版本
    2. 下载源码并编译。

      tar -zxvf mongo-java-driver-r3.5.0.tar.gz

      cd mongo-java-driver-r3.5.0

      gradle mongo-java-driver:jar

  3. Java程序连接实例的示例代码:
    import java.util.ArrayList;
    import java.util.List;
    import org.bson.Document;
    import org.bson.BsonDocument;
    import org.bson.BsonString;
    import com.mongodb.MongoClient;
    import com.mongodb.MongoClientOptions;
    import com.mongodb.MongoClientURI;
    import com.mongodb.MongoCredential;
    import com.mongodb.MongoException;
    import com.mongodb.ServerAddress;
    import com.mongodb.client.MongoCollection;
    import com.mongodb.client.MongoDatabase;
    import com.mongodb.client.MongoCursor;
    
    public class Demo {
        public static String DEFAULT_DB = "admin";
        public static String TEST_DB = "mydb";
        public static String TEST_COLL = "mycoll";
    
        public static MongoClient createDefaultMongoClient(){
            //默认是连接 127.0.0.1:27017 ,
            return new MongoClient();
        }
    
        public static MongoClient createMongoClientByURI(String uri){
            MongoClientOptions.Builder builder = MongoClientOptions.builder().socketTimeout(2000).connectionsPerHost(1);
            MongoClientURI curi = new MongoClientURI(uri,builder);
            return new MongoClient(curi);
        }
    
        public static MongoClient createMongoClientByServerAddress(List<ServerAddress> seedList,String username,String passwd){
            List<MongoCredential> credentials = new ArrayList<MongoCredential>();
            credentials.add(MongoCredential.createCredential(username, DEFAULT_DB,passwd.toCharArray()));
            MongoClientOptions options = MongoClientOptions.builder().socketTimeout(2000).build(); 
            return new MongoClient(seedList,credentials,options);
        }
    
        public void main(String[] args) {
            /*
            * create MongoClient By URI
            * recommand
            */
            //可以复制增强版实例基本信息页面提供的连接信息
            //例如 mongodb://rwuser:****@10.10.10.10:8635,10.10.10.11:8635/test?authSource=admin
            String uri = "mongodb://rwuser:****@10.10.10.10:8635,10.10.10.11:8635/mydb?authSource=admin";
            MongoClient client = createMongoClientByURI(uri);
    
            /*OR create MongoClient By ServerAddress*/
            //String mongos_ip_1 = "192.168.1.129";
            //int mongos_port_1 = 8635;
            //String mongos_ip_2 = "192.168.1.123";
            //int mongos_port_2 = 8635;
            //String username = "rwuser";
            //passwd = "******";
            //List<ServerAddress> seedList = new ArrayList<ServerAddress>();
            //seedList.add(new ServerAddress(mongos_ip_1,mongos_port_1));
            //seedList.add(new ServerAddress(mongos_ip_2,mongos_port_2));
            //MongoClient client = createMongoClientByServerAddress(seedList,username,passwd);
    
            /*OR create Default MongoClient*/
            //MongoClient client = createDefaultMongoClient()
    
           try{
                MongoDatabase database = client.getDatabase(TEST_DB);
                MongoCollection<Document> collection = database.getCollection(TEST_COLL);
                // 插入
                Document doc = new Document();
                doc.append("student_num", 1).append("student_name", "LIMING").append("score", 89);
                
                collection.insertOne(doc);
                // 查询
                BsonDocument query = new BsonDocument();
                query.append("student_num", new BsonString("1"));
                MongoCursor<Document> cursor = collection.find(query).iterator();
                while (cursor.hasNext()) {
                    System.out.println("find document: " + cursor.next());
                }
           }catch(IllegalArgumentException e){
                //TODO SOMETHING ELSE
               e.printStackTrace();?
           }catch(MongoException e){
               //TODO SOMETHING ELSE
               e.printStackTrace();
           }finally{
               client.close();
           }
        }
    }

C 程序连接示例

  1. 下载并安装mongo-c-driver 1.8版本
  2. C程序连接实例的示例代码:
    #include <assert.h>
    #include <bcon.h>
    #include <mongoc.h>
    #include <stdio.h>
    
    static void bulk1 (mongoc_collection_t *collection)
    {
       mongoc_bulk_operation_t *bulk;
       bson_error_t error;
       bson_t *doc;
       bson_t reply;
       char *str;
       bool ret;
       int i;
    
       bulk = mongoc_collection_create_bulk_operation (collection, true, NULL);
    
       for (i = 0; i < 10000; i++) {
          doc = BCON_NEW ("i", BCON_INT32 (i));
          mongoc_bulk_operation_insert (bulk, doc);
          bson_destroy (doc);
       }
    
       ret = mongoc_bulk_operation_execute (bulk, &reply, &error);
    
       str = bson_as_canonical_extended_json (&reply, NULL);
       printf ("%s\n", str);
       bson_free (str);
    
       if (!ret) {
          fprintf (stderr, "Error: %s\n", error.message);
       }
    
       bson_destroy (&reply);
       mongoc_bulk_operation_destroy (bulk);
    }
    int main (int argc, char *argv[])
    {
       mongoc_client_t *client;
       mongoc_collection_t *collection;
    
       mongoc_init ();
       //可以复制增强版实例基本信息页面提供的连接信息
       //例如 mongodb://rwuser:****@10.10.10.10:8635,10.10.10.11:8635/test?authSource=admin
       client = mongoc_client_new ("mongodb://rwuser:****@10.10.10.10:8635,10.10.10.11:8635/test?authSource=admin");
       mongoc_client_set_error_api (client, 2);
       collection = mongoc_client_get_collection (client, "test", "test");
    
       bulk1 (collection);
    
       mongoc_collection_destroy (collection);
       mongoc_client_destroy (client);
    
       mongoc_cleanup ();
    
       return 0;
    }
分享:

    相关文档

    相关产品

文档是否有解决您的问题?

提交成功!

非常感谢您的反馈,我们会继续努力做到更好!

反馈提交失败,请稍后再试!

*必选

请至少选择或填写一项反馈信息

字符长度不能超过200

提交反馈 取消

如您有其它疑问,您也可以通过华为云社区问答频道来与我们联系探讨

跳转到云社区