连接到MongoDB Atlas从AWS Lambda花费太长时间。

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

Connecting to MongoDB Atlas from AWS Lambda takes too long

问题

The cold start takes approx. 10 seconds which is unacceptable for me. If lambda reuses the connection, the duration decreases to 30ms. Is there any way how to improve initial connection time?

冷启动大约需要10秒,这对我来说是不可接受的。如果Lambda重用连接,持续时间将减少到30毫秒。是否有任何方法来改善初始连接时间?

The most time-consuming part (6 seconds)

最耗时的部分(6秒)

2020-08-04T20:39:45.004+02:00
INFO: No server chosen by com.mongodb.client.internal.MongoClientDelegate from cluster description ClusterDescription{type=REPLICA_SET, connectionMode=MULTIPLE, serverDescriptions=[ServerDescription{<shard>, type=UNKNOWN, state=CONNECTING}, ServerDescription{<shard>, type=UNKNOWN, state=CONNECTING}, ServerDescription{<shard>, type=UNKNOWN, state=CONNECTING}]}. Waiting for 30000 ms before timing out

2020-08-04T20:39:51.302+02:00
Aug 04, 2020 6:39:51 PM com.mongodb.diagnostics.logging.JULLogger log

2020-08-04T20:39:45.004+02:00
INFO: com.mongodb.client.internal.MongoClientDelegate未选择任何服务器,来自集群描述ClusterDescription的连接模式{type=REPLICA_SET,connectionMode=MULTIPLE,serverDescriptions=[ServerDescription{<shard>,type=UNKNOWN,state=CONNECTING},ServerDescription{<shard>,type=UNKNOWN,state=CONNECTING},ServerDescription{<shard>,type=UNKNOWN,state=CONNECTING}]}。在超时之前等待30000毫秒。

2020-08-04T20:39:51.302+02:00
2020年8月4日 下午6:39:51 com.mongodb.diagnostics.logging.JULLogger记录

import com.amazonaws.services.lambda.runtime.RequestHandler;
import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent;
import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent;

import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;

public class MongoDBConnectionLambdaHandler implements RequestHandler&lt;APIGatewayProxyRequestEvent, APIGatewayProxyResponseEvent&gt; {

    // declare MongoClient as an instance variable to ensure connection pooling
    private MongoClient mongoClient = null;

    @Override
    public APIGatewayProxyResponseEvent handleRequest(APIGatewayProxyRequestEvent request, Context context) {

        MongoDatabase database = getDBConnection(context);

        APIGatewayProxyResponseEvent response = new APIGatewayProxyResponseEvent();
        Document doc = database.getCollection(System.getenv(&quot;MONGO_DB_COLLECTION&quot;))
                               .find()
                               .first();

        response.setBody(doc == null ? null : doc.toJson());

        response.setStatusCode(200);
        return response;
    }

    private MongoDatabase getDBConnection(Context context) {

        if (mongoClient == null) {

            context.getLogger().log(&quot;Initializing new MongoDB connection&quot;);
            mongoClient = MongoClients.create(System.getenv(&quot;MONGO_DB_URI&quot;));
            return mongoClient.getDatabase(System.getenv(&quot;MONGO_DB_NAME&quot;));
        }

        context.getLogger().log(&quot;Reusing existing MongoDB connection&quot;);
        return mongoClient.getDatabase(System.getenv(&quot;MONGO_DB_NAME&quot;));
    }

}
英文:

The cold start takes approx. 10 seconds which is unacceptable for me. If lambda reuses the connection, the duration decreases to 30ms. Is there any way how to improve initial connection time?

The most time-consuming part (6 seconds)

2020-08-04T20:39:45.004+02:00
INFO: No server chosen by com.mongodb.client.internal.MongoClientDelegate from cluster description ClusterDescription{type=REPLICA_SET, connectionMode=MULTIPLE, serverDescriptions=[ServerDescription{<shard>, type=UNKNOWN, state=CONNECTING}, ServerDescription{<shard>, type=UNKNOWN, state=CONNECTING}, ServerDescription{<shard>, type=UNKNOWN, state=CONNECTING}]}. Waiting for 30000 ms before timing out

2020-08-04T20:39:51.302+02:00
Aug 04, 2020 6:39:51 PM com.mongodb.diagnostics.logging.JULLogger log

import com.amazonaws.services.lambda.runtime.RequestHandler;
import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent;
import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent;

import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;

public class MongoDBConnectionLambdaHandler implements RequestHandler&lt;APIGatewayProxyRequestEvent, APIGatewayProxyResponseEvent&gt; {

    // declare MongoClient as an instance variable to ensure connection pooling
    private MongoClient mongoClient = null;

    @Override
    public APIGatewayProxyResponseEvent handleRequest(APIGatewayProxyRequestEvent request, Context context) {

        MongoDatabase database = getDBConnection(context);

        APIGatewayProxyResponseEvent response = new APIGatewayProxyResponseEvent();
        Document doc = database.getCollection(System.getenv(&quot;MONGO_DB_COLLECTION&quot;))
                               .find()
                               .first();

        response.setBody(doc == null ? null : doc.toJson());

        response.setStatusCode(200);
        return response;
    }

    private MongoDatabase getDBConnection(Context context) {

        if (mongoClient == null) {

            context.getLogger().log(&quot;Initializing new MongoDB connection&quot;);
            mongoClient = MongoClients.create(System.getenv(&quot;MONGO_DB_URI&quot;));
            return mongoClient.getDatabase(System.getenv(&quot;MONGO_DB_NAME&quot;));
        }

        context.getLogger().log(&quot;Reusing existing MongoDB connection&quot;);
        return mongoClient.getDatabase(System.getenv(&quot;MONGO_DB_NAME&quot;));
    }

}

</details>


# 答案1
**得分**: 1

我成功将初始连接时间缩短了2秒,通过在处理程序方法外触发连接。剩下的时间可能是语言选择的结果。

```import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent;
import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent;

import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;

import org.bson.Document;

public class MongoDBConnectionHandler implements RequestHandler&lt;APIGatewayProxyRequestEvent, APIGatewayProxyResponseEvent&gt; {

    // 将MongoClient声明为实例变量以确保连接池
    private final MongoClient mongoClient = MongoClients.create(System.getenv(&quot;MONGO_DB_URI&quot;));

    @Override
    public APIGatewayProxyResponseEvent handleRequest(APIGatewayProxyRequestEvent request, Context context) {

        APIGatewayProxyResponseEvent response = new APIGatewayProxyResponseEvent();
        Document doc = mongoClient.getDatabase(System.getenv(&quot;MONGO_DB_NAME&quot;))
                                  .getCollection(System.getenv(&quot;MONGO_DB_COLLECTION&quot;))
                                  .find()
                                  .first();

        response.setBody(doc == null ? null : doc.toJson());

        response.setStatusCode(200);
        return response;
    }

}```

<details>
<summary>英文:</summary>

I managed to cut down the initial connection time by 2 seconds by triggering a connection outside the handler method. The remaining time is probably a result of language choice.

```import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent;
import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent;

import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;

import org.bson.Document;

public class MongoDBConnectionHandler implements RequestHandler&lt;APIGatewayProxyRequestEvent, APIGatewayProxyResponseEvent&gt; {

    // declare MongoClient as an instance variable to ensure connection pooling
    private final MongoClient mongoClient = MongoClients.create(System.getenv(&quot;MONGO_DB_URI&quot;));

    @Override
    public APIGatewayProxyResponseEvent handleRequest(APIGatewayProxyRequestEvent request, Context context) {

        APIGatewayProxyResponseEvent response = new APIGatewayProxyResponseEvent();
        Document doc = mongoClient.getDatabase(System.getenv(&quot;MONGO_DB_NAME&quot;))
                                  .getCollection(System.getenv(&quot;MONGO_DB_COLLECTION&quot;))
                                  .find()
                                  .first();

        response.setBody(doc == null ? null : doc.toJson());

        response.setStatusCode(200);
        return response;
    }

}


</details>



huangapple
  • 本文由 发表于 2020年8月5日 03:08:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/63253580.html
匿名

发表评论

匿名网友

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

确定