MongoDB database Connection Pool (Java edition)

Source: Internet
Author: User
Tags connection pooling mongoclient

    • The Java driver I used was version 2.13
      1. Driven by: http://mongodb.github.io/mongo-java-driver/
      2. The corresponding API address is: http://api.mongodb.org/java/2.13/
    • Design of MongoDB Database interface
 Packagestorm.db;Importjava.util.ArrayList;ImportCom.mongodb.DB;Importcom.mongodb.DBCollection;ImportCom.mongodb.DBObject;/*** Class Name: mongodbdao* lky*/ Public InterfaceMongodbdao {/*** * Method Name: GETDB * lky * Description: Get the specified MongoDB database *@paramDbName *@return     */     PublicDB getdb (String dbName); /*** * Method Name: GetCollection * lky * Description: Gets the collection collection of the specified MongoDB database *@paramdbName Database name *@paramCollectionName Database collection name *@return     */     Publicdbcollection getcollection (String dbName, string collectionname); /*** * Method Name: InSert * lky * Description: Add the given keys and corresponding values to the specified database *@paramDbName *@paramCollectionName *@paramKeys *@paramvalues *@return     */     Public BooleanInSert (String dbName, String collectionname, string keys, Object values); /*** * Method Name: Delete * lky * Description: Delete database dbname, specify the keys and values of the corresponding value *@paramDbName *@paramCollectionName *@paramKeys *@paramvalues *@return     */     Public BooleanDelete (string dbName, String collectionname, string keys, Object values); /*** Method Name: Find * lky * Description: Remove the corresponding number of data from the database dbname *@paramDbName *@paramCollectionName *@paramKeys *@paramvalues *@paramnum *@return     */     PublicArraylist<dbobject> Find (String dbName, String CollectionName,intnum); /*** * Method Name: UPDATE * LKY * Description: Updates database dbname, updates oldvalue with the specified newvalue *@paramDbName *@paramCollectionName *@paramOldValue *@paramNewValue *@return     */     Public BooleanUpdate (String dbName, String collectionname, DBObject oldValue, DBObject newvalue); /*** Method Name: Isexit * lky * Description: Determines whether the given keys and corresponding values exist in the CollectionName collection of the specified dbname *@paramDbName *@paramCollectionName *@paramKeys *@paramvalues *@return     */     Public Booleanisexit (String dbName, String CollectionName, String key, Object value);}
    • Implementation of database connection pooling
 Packagestorm.db;Importjava.net.UnknownHostException;Importjava.util.ArrayList;ImportCom.mongodb.BasicDBObject;ImportCom.mongodb.DB;Importcom.mongodb.DBCollection;ImportCom.mongodb.DBCursor;ImportCom.mongodb.DBObject;Importcom.mongodb.MongoClient;Importcom.mongodb.MongoClientOptions;Importcom.mongodb.ServerAddress;ImportCom.mongodb.WriteResult;/** MongoDB database link Pool*/ Public classMongodbdaoimplImplementsmongodbdao{PrivateMongoclient mongoclient =NULL; Private Static FinalMongodbdaoimpl Mongodbdaoimpl =NewMongodbdaoimpl ();//a hungry man single-case mode    PrivateMongodbdaoimpl () {if(Mongoclient = =NULL) {Mongoclientoptions.builder buide=NewMongoclientoptions.builder (); Buide.connectionsperhost (100);//Maximum number of links that can be established with the target databaseBuide.connecttimeout (1000 * 60 * 20);//time-out period to establish links to the databaseBuide.maxwaittime (100 * 60 * 5);//maximum wait time for a thread to successfully get to an available databaseBuide.threadsallowedtoblockforconnectionmultiplier (100); Buide.maxconnectionidletime (0); Buide.maxconnectionlifetime (0); Buide.sockettimeout (0); Buide.socketkeepalive (true); Mongoclientoptions myoptions=Buide.build (); Try{mongoclient=NewMongoclient (NewServerAddress ("127.0.0.1", 27017), myoptions); } Catch(unknownhostexception e) {e.printstacktrace (); }        }    }     Public StaticMongodbdaoimpl Getmongodbdaoimpl () {returnMongodbdaoimpl; } @Override PublicDB getdb (String dbName) {returnMongoclient.getdb (dbName); } @Override Publicdbcollection getcollection (String dbName, String collectionname) {db db=Mongoclient.getdb (dbName); returndb.getcollection (CollectionName); } @Override Public BooleanInSert (String dbName, String collectionname, string keys, Object values) {db db=Mongoclient.getdb (dbName); Dbcollection dbcollection=db.getcollection (CollectionName); Longnum =Dbcollection.count (); Basicdbobject Doc=NewBasicdbobject ();        Doc.put (keys, values);        Dbcollection.insert (DOC); if(Dbcollection.count ()-num > 0) {System.out.println ("Add Data Success!!!" "); return true; }        return false; } @Override Public BooleanDelete (string dbName, String collectionname, string keys, Object values) {Writeresult Writeresult=NULL; DB DB=Mongoclient.getdb (dbName); Dbcollection dbcollection=db.getcollection (CollectionName); Basicdbobject Doc=NewBasicdbobject ();        Doc.put (keys, values); Writeresult=Dbcollection.remove (DOC); if(WRITERESULT.GETN () > 0) {System.out.println ("DELETE data successfully!!!!"); return true; }        return false; } @Override PublicArraylist<dbobject> Find (String dbName, String CollectionName,intnum) {        intCount=num; ArrayList<DBObject> list =NewArraylist<dbobject>(); DB DB=Mongoclient.getdb (dbName); Dbcollection dbcollection=db.getcollection (CollectionName); Dbcursor dbcursor=Dbcollection.find (); if(num = =-1)        {             while(Dbcursor.hasnext ()) {List.add (Dbcursor.next ()); }        } Else        {             while(Dbcursor.hasnext ()) {if(count==0) Break;                List.add (Dbcursor.next ()); Count--; }        }        returnlist; } @Override Public BooleanUpdate (String dbName, String collectionname, DBObject oldValue, DBObject newvalue) {Writeresult Writeresul T=NULL; DB DB=Mongoclient.getdb (dbName); Dbcollection dbcollection=db.getcollection (CollectionName); Writeresult=dbcollection.update (OldValue, newvalue); if(WRITERESULT.GETN () > 0) {System.out.println ("Data Update succeeded"); return true; }        return false; } @Override Public Booleanisexit (String dbName, String CollectionName, String key, Object value) {db DB=Mongoclient.getdb (dbName); Dbcollection dbcollection=db.getcollection (CollectionName); Basicdbobject Doc=NewBasicdbobject ();        Doc.put (key, value); if(Dbcollection.count (DOC) > 0)        {            return true; }        return false; }     Public Static voidMain (String args[]) {Mongodbdaoimpl Mongodbdaoimpl=Mongodbdaoimpl.getmongodbdaoimpl (); ArrayList<DBObject> list=NewArraylist<dbobject>(); List=mongodbdaoimpl.find ("JD", "Phone",-1);    System.out.println (List.size ()); }}

Note: The implementation of the database connection pool is a singleton pattern (lazy type)

MongoDB database Connection Pool (Java edition)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.