MongoDB connection method learning

Source: Internet
Author: User

MongoDB needs to be used in the project. According to the introduction, the connection pool idea of MongoDB can be used to maintain only one instance,

Refer to Region.

Package CN. CNIC. jingshao. mongodbapp. util; import java.net. unknownhostexception; import COM. mongoDB. DB; import COM. mongoDB. mongo; import COM. mongoDB. except exception; import COM. mongoDB. optional options; public class mongodbutil {// The only Mongo instance private Mongo; // use the singleton mode private mongodbutil () {} Private Static class innerholder {static final includbutil instance = new includbutil ();} public static includbutil getinst Ance () {return innerholder. instance;}/*** initialize MongoDB connection * @ throws unknownhostexception * @ throws unknown exception */Public void Init () throws unknownhostexception, except exception {int poolsize = configutil. getinstance (). getpoolsize (); // Number of connections read from the configuration file if (poolsize =-1) {poolsize = 10000;} system. setproperty ("Mongo. poolsize ", String. valueof (poolsize); If (this. mongo = NULL) {// system. out. println ("1st init m Ongo instance "); // Mongo instance is instantiated only once // read the server address and port number from the configuration file string serverip = configutil. getinstance (). getserverip (); int portnum = configutil. getinstance (). getportnum (); Mongo = new Mongo (serverip, portnum); Optional options = Mongo. getaskoptions (); options. autoconnectretry = true; options. connectionsperhost = poolsize ;}}/*** get dB instance * @ Param dbname * @ return */Public dB getdb (string dbname) {If (dbname! = NULL &&! Dbname. equals ("") {return this. mongo. getdb (dbname);} else {return NULL;}/*** close MongoDB */Public void close () {If (this. mongo! = NULL) {This. Mongo. Close (); this. Mongo = NULL ;}}}

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.