Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Interpretation of mongodb Source Code for java connection

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >

Share

Shulou(Shulou.com)06/01 Report--

Mongdb has been used for more than half a year, and it has always been OK to implement the logic of the business. However, this does not progress…So today I checked the java connection mongodb driver source code, and found a variety of information to integrate it, so that it can be used in depth later.

Paste the connection database code first

List replicaSet = new ArrayList(); replicaSet.add(new ServerAddress("127.0.0.1", 27017)); MongoClientOptions option = MongoClientOptions.builder().autoConnectRetry(true).connectionsPerHost(300).maxWaitTime(30000).build(); MongoConnection.init(replicaSet, option, "test"); public static synchronized void init(List replicaSet, MongoClientOptions option, String defaultDb){ mongo = new MongoClient(replicaSet, option); mongo.setReadPreference(ReadPreference.nearest()); setDb(mongo.getDB(defaultDb)); }

At first glance, it was also a big head, just like the connection mysql database driver memorized by the university, just asking for the exam to be written down without failing the subject. Although it can also be used, but do not understand the attitude is obviously wrong! Let's break it down step by step:

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 ( port != 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, click on it to resolve IP addresses and ports. If the address is 127.0.0.1: 27017, the port after the colon must be 27017, otherwise an exception will be thrown to tell you that you cannot build your own host and port. However, since the construction method with host and port was used, the address and port should be written separately. Why put them together?

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 java encapsulation of ip address, convenient for other network class calls, method internal ipv4 and ipv6 have a variety of detailed decisions, not much detail, after all, is the basic class, there is time to learn carefully to improve will be very large. Details are mentioned in this blog http://my.oschina.net/fhd/blog/371997. volatile is a type modifier. It is designed to modify variables that are accessed and modified by different threads. Without volatile, either multithreaded programs cannot be written, or the compiler loses a lot of optimization opportunities. Going back to the first block, MongoClientOptions are some settings for the database, using the popular builder pattern 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. Let's see one by one ~

connectionsPerHost: Number of connections per host

threadsAllowedToBlockForConnectionMultiplier: Number of thread queues, which multiplied by the connectionsPerHost value above is the thread queue maximum. If the connection thread is full the queue throws an "Out of semaphores to get db" error.

maxWaitTime: Maximum thread blocking time waiting for a connection

connectTimeout: milliseconds of the connection timeout. 0 is default and infinite

socketTimeout: socket timeout. 0 is default and infinite

autoConnectRetry: this controls whether the system automatically retries a connection

The above explanation seems to be common in all kinds of database connection drivers that require thread pools…ReadPrefrence is a setting for read operations when multiple nodes are present. The default is to read only from the master node. There are other attributes such as reading only from the second node, reading from the master node, and reading from the slave node if it is not readable. The previous code was set to read mongo.setReadPreference(ReadPreference.nearest()) from the nearest node. However, our program has only one node…and there is nothing useful about it. WriteConcern is used to ensure the reliability of the writing operation, a balance between performance and reliability, http://kyfxbl.iteye.com/blog/1952941 this blog talks about more details. Simply put, it is to ensure that the write operation is indeed stored, and it will not be reminded when the write fails due to network conditions or server suspension. If this parameter is set to w:-1, no exception information will be obtained. By default, w:1, it is best to set journal:true, and the write operation will be written to the journal file at the same time. In this way, if mongod is abnormally down, the write operation can be restored according to the contents of the journal file after restarting. At a higher level, the cluster is configured for multiple nodes. w: 1 & journal:true is sufficient for only one node. So do we need synchronized in the init method in the first block of code…Since mongo itself is a thread-safe instance, mongoclient inherits mongo, does that mean that there is no need to synchronize when mongoclient is initialized?

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Database

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report