gpt4 book ai didi

java - 我应该保持数据库连接打开以处理每个请求吗?以及如何以正确的方式做到这一点

转载 作者:可可西里 更新时间:2023-11-01 09:58:32 24 4
gpt4 key购买 nike

例如 MongoDB 之类的数据库。我怀疑没有必要为每个请求打开和关闭连接。所以我尝试保持连接来处理这样的每个请求。

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;
}

}

但也许我在某处做错了。我不知道为什么它创建第一个连接并将其留在那里,然后它创建第二个连接并使用它来处理我的数据库请求。这是日志

2018-10-25 11:37:36 INFO  AnnotationMBeanExporter:433 - Registering beans for JMX exposure on startup2018-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/read2018-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 started2018-10-25 11:37:56 INFO  DispatcherServlet:509 - FrameworkServlet 'dispatcherServlet': initialization completed in 39 ms2018-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 out2018-10-25 11:37:56 INFO  connection:71 - Opened connection [connectionId{localValue:1, serverValue:27}] to 10.184.153.232:270172018-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

最佳答案

查找“连接池”,这是让您的请求可以使用的连接“池”保持打开状态的想法。如果它们闲置了一段时间,您可以将它们编程为关闭;相反,如果它们过载,您可以对连接池进行编程以打开更多连接以适应负载。它们可以通过其他方式进行调整/配置。

关于java - 我应该保持数据库连接打开以处理每个请求吗?以及如何以正确的方式做到这一点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52981502/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com