Java Connection MongoDB Source code interpretation

Source: Internet
Author: User
Tags mongoclient volatile

With Mongdb also big six months, has been the logic of the business to achieve the OK. But this does not make progress ... So today checked the Java Connection MongoDB Drive source code, search for a variety of information to integrate, easy to use later in-depth.

Attach Database Code First

 List<ServerAddress> replicaSet = new          ArrayList<ServerAddress> ();          Replicaset.add (new serveraddress ("127.0.0.1",  27017));          MongoClientOptions option =          Mongoclientoptions.builder (). Autoconnectretry (True). Connectionsperhost. Maxwaittime (30000). Build ();          mongoconnection.init (replicaset, option,  "test");  public static synchronized void init (List<serveraddress> replicaset,                    &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;MONGOCLIENTOPTIONS&NBSP;OPTION,&NBSP;STRING&NBSP;DEFAULTDB) {           &nBsp;     mongo = new mongoclient (replicaset, option);                 mongo.setreadpreference ( Readpreference.nearest ());                 setdb (Mongo.getdb (DEFAULTDB));         }

At first glance at the past is also the head of the Titanic, with the university back down the connection MySQL database driver, only to test dictation down not hanging section. Although it can be used, but the attitude of superficial understanding is obviously wrong! Next, take a step-by-step look at it:

    public serveraddress ( String host , int port )         throws UnknownHostException {         if  ( host == null )              host = defaulthost ();         host = host.trim ();        if  ( host.length ( )  == 0 )             host =  defaulthost ();                 int idx = host.indexof (  ":"  );         if  ( idx > 0 ) {             if  (&NBSP;PORT&Nbsp;! = defaultport ()  )                  throw new illegalargumentexception (  "Can ' t specify port in  construct and via host " );             port = integer.parseint ( host.substring ( idx + 1 )  ) ;             host = host.substring (  0 , idx ). Trim ();        }         _host = host;        _port  = port;        updateinetaddress ();     }

Replicaset is obviously an array of server addresses, which is the resolution of the IP address and the port after the point is entered. If the address is 127.0.0.1:27017 style, the port after the colon must be 27017, or throw an exception to tell you that you cannot build the host and port yourself. But since the use of the construction method with host and port, the address and ports are written separately, why put in a piece ...

Boolean updateinetaddress () throws unknownhostexception {inetsocketaddress oldaddress = _address;        _address = new Inetsocketaddress (Inetaddress.getbyname (_host), _port);    Return!_address.equals (oldaddress); } volatile inetsocketaddress _address;

As for Updateinetaddress (), inetaddress is the Java IP Address encapsulation, convenient for other network class calls, methods within the IPv4 and IPv6 have a variety of detailed judgment, not many, after all, is the basic class, there is time to seriously study the promotion will be very large. Detailed content in this blog inside http://my.oschina.net/fhd/blog/371997 has mentioned. Volatile is a type modifier (type specifier). It is designed to modify variables that are accessed and modified by different threads. If you do not add volatile, you cannot write multithreaded programs, or the compiler loses a lot of optimization opportunities. Back to the first block, Mongoclientoptions is a few settings for the database, used by the people to the builder Mode builder:

        private String description;         private int connectionsPerHost = 100;         private int threadsAllowedToBlockForConnectionMultiplier = 5;         private int maxwaittime = 1000 *  60 * 2;        private int connecttimeout  = 1000 * 10;        private int  sockettimeout = 0;        private boolean  socketkeepalive = false;        private boolean  autoconnectretry = false;        private long  maxautoconnectretrytime = 0;        private ReadPreference readPreference =  Readpreference.primary ();        private dbdecoderfactory  Dbdecoderfactory = defaultdbdecoder.factory;        private  DBEncoderFactory dbEncoderFactory = DefaultDBEncoder.FACTORY;         private WriteConcern writeConcern = WriteConcern.ACKNOWLEDGED;         private SocketFactory socketFactory =  Socketfactory.getdefault ();        private boolean  Cursorfinalizerenabled = true;        private boolean  alwaysUseMBeans = false;

Builder assigns values to member variables that need to be initialized. One by one, see ~

    • Connectionsperhost: Number of connections per host

    • Threadsallowedtoblockforconnectionmultiplier: The number of thread queues, the result of which is multiplied by the above Connectionsperhost value is the maximum thread queue value. The "out of semaphores to get DB" error is thrown if the connection thread is fully queued.

    • Maxwaittime: The maximum waiting time for a connected thread to block

    • ConnectTimeout: The milliseconds that the connection timed out. 0 is the default and unlimited

    • Sockettimeout:socket timeout. 0 is the default and unlimited

    • Autoconnectretry: If this control is in a connection, the system will automatically retry

The above explanations seem to be common in a variety of database connection drivers that require a thread pool ... Readprefrence is a set of read operations for multiple nodes, which is read from the primary node by default, and other properties such as reading from the second node only, reading from the master node, reading from the node if not readable, and so on. It hasn't been used yet. The previous code was set to read Mongo.setreadpreference (Readpreference.nearest ()) from the nearest node. However, our program has only one node ... And there's no egg to use. Writeconcern is used to ensure the reliability of write operations, is a balance between performance and reliability, http://kyfxbl.iteye.com/blog/1952941 this blog in more detail. Simple is to ensure that the write operation is actually in the storage, not because the network condition or the server hangs to fail to get a reminder when the write fails, if this parameter setting w:-1 will not get any exception information, the default w:1, preferably also set jurnal:true, The write operation writes to the memory as well as to the journal file, so that if Mongod is not properly down, a restart can be done to restore the write based on the contents of the journal file. The higher level is set up for clusters of multiple nodes, with only one node w:1&journal:true enough. So the synchronized in the Init method in the first piece of code need not ... MONGO since it is a thread-safe instance, Mongoclient inherits MONGO, doesn't mean it doesn't need to be synchronized when initializing mongoclient.


This article is from the "9445703" blog, please be sure to keep this source http://9455703.blog.51cto.com/9445703/1763875

Java Connection MongoDB Source code interpretation

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.