For example a database such as MongoDB. I doubt that it is unnecessary to open and close a connection for every request. So I try to keep a connection to handle every request like this.
public class MongoUtils {
private static final String connectionString = "mongodb://localhost:27017";
private static final MongoClient client;
static {
client = MongoClients.create(connectionString);
}
public static MongoClient getConnection(){
return client;
}
}
But maybe I'm doing this wrong somewhere. I don't know why it create the first connection and leave it there, then it create the second connection and use that to handle my db request. Here's the log
2018-10-25 11:37:36 INFO AnnotationMBeanExporter:433 - Registering beans for JMX exposure on startup 2018-10-25 11:37:36 INFO Http11NioProtocol:180 - Starting ProtocolHandler ["http-nio-8808"] 2018-10-25 11:37:36 INFO NioSelectorPool:180 - Using a shared selector for servlet write/read 2018-10-25 11:37:36 INFO TomcatWebServer:206 - Tomcat started on port(s): 8808 (http) with context path '/api' 2018-10-25 11:37:36 INFO Backend:59 - Started Backend in 3.251 seconds (JVM running for 6.935) 2018-10-25 11:37:56 INFO [/api]:180 - Initializing Spring FrameworkServlet 'dispatcherServlet' 2018-10-25 11:37:56 INFO DispatcherServlet:494 - FrameworkServlet 'dispatcherServlet': initialization started 2018-10-25 11:37:56 INFO DispatcherServlet:509 - FrameworkServlet 'dispatcherServlet': initialization completed in 39 ms 2018-10-25 11:37:56 INFO cluster:71 - Cluster created with settings {hosts=[10.184.153.232:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500} 2018-10-25 11:37:56 INFO cluster:71 - Cluster description not yet available. Waiting for 30000 ms before timing out 2018-10-25 11:37:56 INFO connection:71 - Opened connection [connectionId{localValue:1, serverValue:27}] to 10.184.153.232:27017 2018-10-25 11:37:56 INFO cluster:71 - Monitor thread successfully connected to server with description ServerDescription{address=10.184.153.232:27017, type=STANDALONE, state=CONNECTED, ok=true, version=ServerVersion{versionList=[4, 0, 3]}, minWireVersion=0, maxWireVersion=7, maxDocumentSize=16777216, logicalSessionTimeoutMinutes=30, roundTripTimeNanos=3393851} 2018-10-25 11:37:56 INFO connection:71 - Opened connection [connectionId{localValue:2, serverValue:28}] to 10.184.153.232:27017