MongoDB连接立即关闭 – Java

huangapple go评论100阅读模式
英文:

MongoDB connection instantly closes - Java

问题

我正在使用 mongodb-driver-sync-4.1.0-rc0 依赖项,每当我连接到数据库时,我可以在同一个方法内使用它,但一旦将它存储为静态变量并尝试从另一个类中访问它时,它会显示“状态应为:打开”。在建立连接后,我的连接立即关闭。

public static void initializeClient(){
    String uri = "mongodb+srv://myusername:mypassword@userstats.9vs4b.mongodb.net/izzi?retryWrites=true&w=majority";

    try ( MongoClient mongoClient = MongoClients.create(uri)) {

        client = mongoClient;
        izzi = client.getDatabase("izzi").getCollection("userStats");

        System.out.println(getOverallLikes());
        System.out.println(getWinnersLastMonth());
        //after this it closes the connection

    }
}

当它断开连接时,我收到这个消息:[main] INFO org.mongodb.driver.connection - Closed connection [connectionId{localValue:4, serverValue:14654}] to userstats-shard-00-02.9vs4b.mongodb.net:27017 because the pool has been closed.

英文:

I am using the mongodb-driver-sync-4.1.0-rc0 dependency and whenever I connect to the database I can use it within the same method but as soon as i store it as a static var and try accessing it from another class it says "state should be: open". My connection instantly closes after establishing a connection.

public static void initializeClient(){
        String uri = "mongodb+srv://myusername:mypassword@userstats.9vs4b.mongodb.net/izzi?retryWrites=true&w=majority";

        try ( MongoClient mongoClient = MongoClients.create(uri)) {

            client = mongoClient;
            izzi = client.getDatabase("izzi").getCollection("userStats");

            System.out.println(getOverallLikes());
            System.out.println(getWinnersLastMonth());
            //after this it closes the connection

        }
    }

I get this message when it disconnects: [main] INFO org.mongodb.driver.connection - Closed connection [connectionId{localValue:4, serverValue:14654}] to userstats-shard-00-02.9vs4b.mongodb.net:27017 because the pool has been closed.

答案1

得分: 2

它的行为是正常的; 这是一个 try-with-resources:

try ( MongoClient mongoClient = MongoClients.create(uri)) 
{
       client = mongoClient;
       izzi = client.getDatabase("izzi").getCollection("userStats");
       System.out.println(getOverallLikes());
       System.println(getWinnersLastMonth());
       // 在此之后它关闭连接
}

从文档中:

try-with-resources 语句是一个 try 语句,声明一个或多个资源。资源是在程序完成后必须关闭的对象。try-with-resources 语句确保在语句结束时关闭每个资源。

您的资源是 MongoClient 实例,它将在 try 子句内的最后操作后自动关闭。由于您将 mongoClient 的值分配给 client 变量,一旦 try 子句完成并关闭了 mongoClientclient 将引用一个已关闭的会话。

英文:

Its behaviour is the normal one; This is a try-with-resources:

try ( MongoClient mongoClient = MongoClients.create(uri)) 
{
       client = mongoClient;
       izzi = client.getDatabase("izzi").getCollection("userStats");
       System.out.println(getOverallLikes());
       System.out.println(getWinnersLastMonth());
       //after this it closes the connection
}

From the documentation:

The try-with-resources statement is a try statement that declares one or more resources. A resource is an object that must be closed after the program is finished with it. The try-with-resources statement ensures that each resource is closed at the end of the statement

Your resource is the MongoClient instance, which will be automatically closed after the last operation inside the try clause. As you assigned the mongoClient value to your client variable, once the try-clause is finished and the mongoClient closed, client will reference a closed session.

答案2

得分: 0

以上观察到连接关闭的情况符合Java的 'try with resources' 功能的预期功能。

通过使用 常规的 try ... catch ... finally 块 并显式调用 mongoClient.close() 可以实现保持连接处于活动状态的期望要求。

此外,如果要求是从不同的类中调用该方法,那么关闭连接的代码需要放在不同的方法中。

工作代码片段:

(a) 连接到MongoDB,获取数据并关闭连接:

public void myMongoDBClient() {
    MongoClient mongoClient;
    String uri = "mongodb-connection-uri";
    try {
         mongoClient = new MongoClient(uri)

         // 从mongodb获取数据
         // 其他语句

    } catch (Exception ex) {
       // 错误处理

    } finally {
       // 关闭连接
       mongoClient.close();
    }
}

(b) 从其他类调用MongoDB客户端:

public class MyMongoDBClient {

    private static MongoClient mongoClient = null;
    private static String uri = "mongodb-connection-uri";

    public static void initializeClient() {
        try {
             mongoClient = new MongoClient(uri)

        } catch (Exception ex) {
           // 错误处理

        } finally {
           // 关闭连接
           mongoClient.close();
        }
    }

   public static void fetchData() throws Exception {
       // 获取数据的代码
       // 可以从外部类多次调用
   }

  public static void close() throws Exception {
      // 关闭连接
      // 可以从外部类调用一次
      mongoClient.close();
  }
}
英文:

The above observation of connection being closed is as per the intended functionality of the 'try with resources' feature of Java.

The desired requirement of keeping the connection active can be achieved by using a regular try ... catch ... finally block with mongoClient.close() called explicitly for closing the connection.

Moreover, if the requirement is to call the method from a different class, then the code for closing the connection need to be placed in a different method.

Working code snippets:

(a) Connect to MongoDB, fetch data and close connection:

    public void myMongoDBClient() {
        MongoClient mongoClient;
        String uri = "mongodb-connection-uri";
        try {
             mongoClient = new MongoClient(uri)

             // Fetch data from mongodb
             // Other statements


        } catch (Exception ex) {
           // Error handling

        } finally {
           // Close the conection
           mongoClient.close();
        }
    }

(b) Call mongodb client from other classes:

public class MyMongoDBClient {

    private static MongoClient mongoClient = null;
    private static String uri = "mongodb-connection-uri";

    public static void initializeClient() {
        try {
             mongoClient = new MongoClient(uri)

        } catch (Exception ex) {
           // Error handling

        } finally {
           // Close the conection
           mongoClient.close();
        }
    }

   public static void fetchData() throws Exception {
       // Code for fetching data
       // Can be called multiple times from external classes
   }

  public static void close() throws Exception {
      // Close connection.
      // Can be called once from an external class
      mongoClient.close();
  }


}

huangapple
  • 本文由 发表于 2020年7月30日 06:11:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/63163179.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定