英文:
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<APIGatewayProxyRequestEvent, APIGatewayProxyResponseEvent> {
// 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("MONGO_DB_COLLECTION"))
.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("Initializing new MongoDB connection");
mongoClient = MongoClients.create(System.getenv("MONGO_DB_URI"));
return mongoClient.getDatabase(System.getenv("MONGO_DB_NAME"));
}
context.getLogger().log("Reusing existing MongoDB connection");
return mongoClient.getDatabase(System.getenv("MONGO_DB_NAME"));
}
}
英文:
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<APIGatewayProxyRequestEvent, APIGatewayProxyResponseEvent> {
// 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("MONGO_DB_COLLECTION"))
.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("Initializing new MongoDB connection");
mongoClient = MongoClients.create(System.getenv("MONGO_DB_URI"));
return mongoClient.getDatabase(System.getenv("MONGO_DB_NAME"));
}
context.getLogger().log("Reusing existing MongoDB connection");
return mongoClient.getDatabase(System.getenv("MONGO_DB_NAME"));
}
}
</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<APIGatewayProxyRequestEvent, APIGatewayProxyResponseEvent> {
// 将MongoClient声明为实例变量以确保连接池
private final MongoClient mongoClient = MongoClients.create(System.getenv("MONGO_DB_URI"));
@Override
public APIGatewayProxyResponseEvent handleRequest(APIGatewayProxyRequestEvent request, Context context) {
APIGatewayProxyResponseEvent response = new APIGatewayProxyResponseEvent();
Document doc = mongoClient.getDatabase(System.getenv("MONGO_DB_NAME"))
.getCollection(System.getenv("MONGO_DB_COLLECTION"))
.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<APIGatewayProxyRequestEvent, APIGatewayProxyResponseEvent> {
// declare MongoClient as an instance variable to ensure connection pooling
private final MongoClient mongoClient = MongoClients.create(System.getenv("MONGO_DB_URI"));
@Override
public APIGatewayProxyResponseEvent handleRequest(APIGatewayProxyRequestEvent request, Context context) {
APIGatewayProxyResponseEvent response = new APIGatewayProxyResponseEvent();
Document doc = mongoClient.getDatabase(System.getenv("MONGO_DB_NAME"))
.getCollection(System.getenv("MONGO_DB_COLLECTION"))
.find()
.first();
response.setBody(doc == null ? null : doc.toJson());
response.setStatusCode(200);
return response;
}
}
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论