如何使 AWS Lambda 通过 websockets 与 Neptune 可靠地工作?

How to make AWS Lambda work reliably with Neptune over websockets?

所以我构建了这个 API。它包含一个 Lambda 函数(可通过 API 网关访问),该函数通过 websockets 与 Neptune 图形数据库实例对话。

一切都已连接并正常工作。但我最近开始注意到来自 API 的间歇性 500。经过一些调查后,我发现 Neptune Gremlin 服务器是 dropping/refusing 连接,只要多个请求靠近在一起。

我发现 this page 这表明无服务器的短暂特性与 websockets 不兼容,因此应在每次请求后手动关闭 websocket 连接。但在实施之后我发现没有区别——仍然是 500 的。

该页面还建议,在 Neptune 上使用 Gremlin 时,您应该向 Neptune 发送 HTTP 请求,而不是使用 websockets,

Alternatively, if you are using Gremlin, consider submitting requests to the Gremlin HTTP REST endpoint rather than the WebSockets endpoint, thereby avoiding the need to create and manage the lifetime of a connection pool.

这种方法的缺点是我们将不得不使用基于字符串的查询(这意味着重写项目的很大一部分)。另一个缺点是 Gremlin HTTP 端点 returns 相当非结构化数据。

所以我想知道是否有人让 Lambda 通过 websockets 可靠地与 Neptune 对话?如果是这样,如何?

编辑:

由于我使用的是 AWS Chalice 框架,所以我认为我无法直接访问处理函数。下面是我的 lambda 的样子。

这里是 connect() 调用的代码:

import os

from gremlin_python.structure.graph import Graph
from gremlin_python.driver.driver_remote_connection import DriverRemoteConnection


def connect():
    conn_string = os.environ.get('GRAPH_DB')
    global g
    g = Graph().traversal().withRemote(DriverRemoteConnection(conn_string, 'g'))

因此,当应用程序启动时(启动 lambda 实例时),将调用该连接函数,并且应用程序会连接到 Neptune。应用程序从那里传递全局 g 变量,以便为该调用使用相同的连接实例。然后我在 DriverRemoteConnection 对象上调用 close(),然后返回请求的结果(这就是我发现我仍然得到 500 的地方)。

是的,可以在 Lambda 函数中使用 WebSockets 与 Neptune 通信。根据您使用的编程语言,执行此操作会有不同的细微差别。最终,它会在 Lambda 函数的 handler() 中实例化客户端连接并关闭连接。

如果使用 Java [1],您可以在处理程序外部创建集群对象,以便每次 Lambda 调用都可以重复使用它。但是从该集群对象配置的客户端必须在每次调用期间被实例化和关闭。

您是否有正在使用的代码片段可以分享以供审阅?

[1] https://docs.aws.amazon.com/neptune/latest/userguide/best-practices-gremlin-java-close-connections.html