MongoDB--mongoclient Connection pool usage

Source: Internet
Author: User
Tags exception handling mongoclient mongodb stub throw exception

The main adjustment is the introduction of the Mongoclient class in the 2.10.0 version, as well as the fact that the MONGO class will be mongoclient replaced in a future version (Note:this class has been superseded by Mongoclient, and May is deprecated in a future release.). Therefore, in this adjustment, the original MongoDB part of the corresponding changes have been made.

Mongoclient is designed to be thread-safe and can be shared by multiple threads. Usually access to the database cluster application requires only one instance, so this time we are designing a single example. If for some reason you decide to use multiple instances, note that all Resource usage restrictions (maximum number of connections, etc.) apply to each mongoclient, and when you destroy an instance, confirm that the Mongoclient.close () method is called to clean up the resource.

The relevant code is given below:

    /** * Project name: Spidercrawler * FileName: Mongodbdao.java * Author: zhouyh * Time: 2014-8-30 03:46:55  

    * Description: TODO (describe what the file does in a word) * * * Package Com.newsTest.dao;  

    Import java.util.ArrayList;  
    Import Com.mongodb.DB;  
    Import com.mongodb.DBCollection;  

    Import Com.mongodb.DBObject; /** * Class Name: Mongodbdao * Package Name: Com.newsTest.dao * Author: zhouyh * Time: 2014-8-30 03:46:55 * Description: To 
         Do (describe the role of this class in one sentence)/public interface Mongodbdao {/** * * Method Name: Getdb * Author: Zhouyh * Create time: 2014-8-30 03:53:40 * Description: Get the specified MongoDB database * @param dbname *  
        return */Public DB getdb (String dbname); /** * * Method Name: GetCollection * Author: zhouyh * Date Created: 2014-8-30 03:54:43 * Description: Gets the collection collection * @param dbname database name * @param collectionname database collection for the specified MongoDB database 
         * @return */Public dbcollection getcollection (String dbname, string collectionname); /** * * Method Name: InSert * Author: zhouyh * Date Created: 2014-8-30 04:07:35 * Description: To  Add the given keys and corresponding values in the specified database * @param dbname * @param collectionname * @param keys * @param values * @return/public boolean InSert (String dbname, String CollectionName, Stri  
        Ng[] keys, object[] values); /** * * Method Name: Delete * Author: zhouyh * Date Created: 2014-8-30 04:09:00 * Description: Delete database db Name, specifies the value of the keys and corresponding values * @param dbname * @param collectionname * @param keys * @p Aram Values * @return */public boolean Delete (String dbname, String CollectionName, string[  
        ] keys, object[] values); /** * * Method Name: Find * Author: zhouyh *Date Created: 2014-8-30 04:11:11 * Description: Finds the value of the specified keys and corresponding values from the database dbname * @param dbname * @param Colle  
        Ctionname * @param keys * @param values * @param num * @return * *  
        Public arraylist<dbobject> Find (String dbname, String CollectionName, string[] keys, object[] values, int num); /** * * Method Name: Update * Author: zhouyh * Date Created: 2014-8-30 04:17:54 * Description: Updates the database dbname, updates the oldvalue * @param dbname * @param collectionname * @param oldva with the specified newvalue Lue * @param newvalue * @return/public boolean update (String dbname, String col  
        Lectionname, DBObject oldValue, DBObject newvalue); /** * * Method Name: Isexit * Author: zhouyh * Date Created: 2014-8-30 04:19:21 * Description: Judge a given Ke YS and corresponding values exist in the specified dbname collectionname collection * @param dbname * @PARAM CollectionName * @param keys * @param values * @return/public b  

    Oolean isexit (String dbname, String CollectionName, String key, Object value);  }
/** * Project Name: Spidercrawler * File name: Mongodbdaoimpl.java * Author: zhouyh * Time: 2014-8-30 04:21:11 * Description: TODO (describe what the file does with a word)

* * Package Com.newsTest.dao.impl;
Import java.net.UnknownHostException;

Import java.util.ArrayList;
Import Com.newsTest.dao.MongoDBDao;
Import Com.mongodb.BasicDBObject;
Import Com.mongodb.DB;
Import com.mongodb.DBCollection;
Import Com.mongodb.DBCursor;
Import Com.mongodb.DBObject;
Import com.mongodb.MongoClient;
Import com.mongodb.MongoClientOptions;
Import com.mongodb.MongoException;

Import Com.mongodb.WriteResult; /** * Class Name: Mongodbdaoimpl * Package Name: Com.newsTest.dao.impl * Author: zhouyh * Time: 2014-8-30 04:21:11 * Description: TODO (describe this class in a word here) With)/public class Mongodbdaoimpl implements mongodbdao{/** * Mongoclient instance represents the database connection pool, is thread safe, can be multi-threaded shared, the client in the multithreaded bar
    To maintain only one instance of the piece * MONGO is not thread-safe, the current MongoDB API has been proposed to replace MONGO/private mongoclient mongoclient = null; /** * * Private constructor * Author: zhouyh/Private Mongodbdaoimpl (){if (mongoclient = null) {Mongoclientoptions.builder build = new Mongoclientoptions.builder ();   Build.connectionsperhost (50);   The maximum number of connection that can be established with the target database is Build.autoconnectretry (true); Automatic re-connect database startup Build.threadsallowedtoblockforconnectionmultiplier (50); If all current connection are in use, then 50 threads per connection can be queued for * * * When a thread accesses the database, the maximum wait time before a successful access to an available database connection is 2 minutes Clock * Here is more dangerous, if more than Maxwaittime did not get this connection, the thread will throw exception * So the Maxwaittime set here should be large enough to avoid due to too many queued threads caused by the data
            Library Access Failed */Build.maxwaittime (1000*60*2);    Build.connecttimeout (1000*60*1);       
            The timeout with the database connection is set to 1 minutes mongoclientoptions myoptions = Build.build ();          
            try {//database connection Instance mongoclient = new Mongoclient ("127.0.0.1", myoptions); catch (Unknownhostexception e) {//TODO here write exception handling code E.printStackTrace ();
            catch (Mongoexception e) {e.printstacktrace (); }}/******** a singleton mode declaration, which is generated in a a hungry man way to ensure thread safety ********************///class initialization, self-instantiation, a hungry man singleton mode private STA
    Tic final Mongodbdaoimpl Mongodbdaoimpl = new Mongodbdaoimpl ();
     /** * * Method Name: Getmongodbdaoimplinstance * Author: zhouyh * Date Created: 2014-8-30 04:29:26 * Description: Single case static Factory method
    * @return */public static Mongodbdaoimpl Getmongodbdaoimplinstance () {return mongodbdaoimpl; /************************ a single case mode declaration end *************************************/@Override public boolean Delete (St
        Ring dbname, String CollectionName, string[] keys, object[] values) {db db = null;
        Dbcollection dbcollection = null;
                if (keys!=null && values!=null) {if (keys.length!= values.length) {//If keys and values are not equal, return false directly
            return false;
    }else{try {                db = Mongoclient.getdb (dbname);    Gets the specified database dbcollection = db.getcollection (CollectionName);    Gets the specified CollectionName set basicdbobject doc = new Basicdbobject ();  Build deletion condition Writeresult result = NULL;

                    Delete Returns the result String resultstring = null;    for (int i=0; i<keys.length; i++) {doc.put (keys[i], values[i]);  Add Delete Condition} result = Dbcollection.remove (DOC);

                    Perform delete operation resultstring = Result.geterror ();   if (null!= db) {try {db.requestdone ();
                        Turn off DB db = null when the request ends; catch (Exception e) {//Todo:handle Exception E.printstacktrac
                        E (); } return (ResulTstring!=null)? False:true;
                    Returns results after a decision is made based on the deletion of the execution result} catch (Exception e) {//Todo:handle Exception
                E.printstacktrace ();   } finally{if (null!= db) {db.requestdone ();
                    Turn off DB db = null;
    }}} return false; @Override Public arraylist<dbobject> Find (String dbname, String CollectionName, string[] Keys
        , object[] values, int num) {arraylist<dbobject> resultlist = new arraylist<dbobject> ();//create returned result set
        DB db = null;
        Dbcollection dbcollection = null;
        dbcursor cursor = NULL;  if (keys!=null && values!=null) {if (keys.length!= values.length) {return resultlist; If the query parameter is correct, return an empty result set}else{the try {db = Mongoclient.getdb (DbnaME);    Gets the database instance dbcollection = Db.getcollection (CollectionName);   Gets the collection set specified in the database basicdbobject queryobj = new Basicdbobject (); Build query condition for (int i=0; i<keys.length; i++) {//Fill query Criteria Queryobj.put (keys[i)
                    , Values[i]);   } cursor = Dbcollection.find (queryobj);
                    Query fetch data int count = 0; if (Num!=-1) {//To determine whether all data is returned, NUM=-1 returns the query for all data, NUM!=-1 returns the specified NUM data while (Count<num && curs
                            Or.hasnext ()) {Resultlist.add (Cursor.next ());
                        count++;
                    return resultlist;
                        }else{while (Cursor.hasnext ()) {Resultlist.add (Cursor.next ());
                 return resultlist;   } catch (Exception e) {//Todo:handle Exception} finally{
                    if (null!= cursor) {cursor.close ();   } if (null!= db) {db.requestdone ();
    Close database Request}}} return resultlist; @Override Public dbcollection getcollection (String dbname, String collectionname) {//TODO Auto-genera
    Ted method stubs return Mongoclient.getdb (dbname). GetCollection (CollectionName); @Override public DB getdb (String dbname) {//TODO auto-generated a stub return Mongoclien
    T.getdb (dbname); @Override public boolean InSert (String dbname, String CollectionName, string[] keys, object[] Value
        s) {db db = null;
        Dbcollection dbcollection = null; Writeresult result = nulL
        String resultstring = null;
            if (keys!=null && values!=null) {if (keys.length!= values.length) {return false; }else{db = Mongoclient.getdb (dbname);//Get database instance dbcollection = Db.getcollection (co    Llectionname);
                Gets the collection set specified in the database basicdbobject insertobj = new Basicdbobject ();
                for (int i=0; i<keys.length; i++) {//Build Add Condition Insertobj.put (Keys[i], values[i]);
                    try {result = Dbcollection.insert (insertobj);
                resultstring = Result.geterror ();
                catch (Exception e) {//Todo:handle Exception e.printstacktrace ();   }finally{if (null!= db) {db.requestdone (); Close db} After the request ends (resultString!= null)?
            False:true;
    return false;
        @Override public boolean Isexit (String dbname, String CollectionName, String key, Object value) {
        TODO auto-generated Method Stub db db = null;
        Dbcollection dbcollection = null;
                if (key!=null && value!=null) {try {db = Mongoclient.getdb (dbname);//Get database instance    Dbcollection = Db.getcollection (CollectionName);    Gets the collection collection specified in the database basicdbobject obj = new Basicdbobject ();

                Construct query condition Obj.put (key, value);
                if (Dbcollection.count (obj) > 0) {return true;
                }else{return false;
            } catch (Exception e) {//Todo:handle Exception e.printstacktrace (); } finally{if (null!= db) {db.requestdone ();  Turn off DB db = null;
    }} return false; @Override Public boolean Update (String dbname, String collectionname, DBObject oldValue, DBObject N
        Ewvalue) {db db = null;
        Dbcollection dbcollection = null;
        Writeresult result = null;

        String resultstring = null;
        if (Oldvalue.equals (NewValue)) {return true; }else{try {db = Mongoclient.getdb (dbname);//Get database instance dbcollection = Db.getco    Llection (CollectionName);
                Gets the specified collection set in the database result = Dbcollection.update (OldValue, newvalue);

                resultstring = Result.geterror (); Return (resultstring!=null)?
            False:true;
            catch (Exception e) {//Todo:handle Exception e.printstacktrace (); } finally{if (null!= db) {db.requEstdone ();
                Turn off DB db = null;
    }} return false;  /** * Method Name: Main * Author: zhouyh * Date Created: 2014-8-30 04:21:11 * Description: TODO (Describe the effect of this method in one sentence) * @param
 args */public static void main (string[] args) {//TODO auto-generated method stub}}
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.