关闭从AWS lambda创建的gremlin集群连接

时间:2018-04-09 22:48:47

标签: aws-lambda gremlin tinkerpop janusgraph gremlin-server

我有一个创建gremlin集群的java lambda:

cluster = Cluster.build()
        .addContactPoints(shuffled.toArray(new String[endpoints.length]))
        .port(Integer.parseInt(port))
        .serializer(new GryoMessageSerializerV1d0(GryoMapper.build().addRegistry(JanusGraphIoRegistry.getInstance())))
        .maxConnectionPoolSize(4096)
        .maxSimultaneousUsagePerConnection(4096)
        .maxInProcessPerConnection(4096)
        .maxWaitForConnection(30000)
        .create();

然后我用这个创建一个Traversal:

final DriverRemoteConnection connection = DriverRemoteConnection.using(cluster).;

final GraphTraversalSource g = TinkerGraph.open().traversal().withRemote(connection);

这是我的问题,创建群集很昂贵,我想每次创建lambda只执行一次,如果重用lambda则重用它。如果我静态地或使用单例构建集群,它将被重用,但是当lambda在每个AWS max lambda生命5分钟后死亡时,从集群创建的连接不会关闭并永远保持打开Gremlin服务器。

1 个答案:

答案 0 :(得分:0)

ShutdownHooks是我发现对确保Gremlin集群在应用程序生命周期结束时关闭有用的一个技巧:

/**
 * Close the clusters held by {@link #ClusterSingleton}. Be aware that the shutdown hooks are not ensured to be executed.
 * For instance:
 * <ol>
 *     <li><code>kill -9</code>: DON'T run the shutdown hook</li>
 *     <li><code>kill -2</code>: Usually run the shutdown hook</li>
 *     <li><code>kill -15</code>: Usually run the shutdown hook</li>
 *     <li><code>CTRL + c</code>: Usually run the shutdown hook</li>
 * </ol>
 */
private static class CloseClusterOnShutdownHook extends Thread {

    @Override
    public void run() {
        Cluster cluster = ClusterSingleton.getInstance()
        try {
            // Not using logger because it may not work during JVM shutdown
            System.out.println("Closing Gremlin Cluster: " + cluster.allHosts());
            cluster.close();
        } catch (Exception ex) {
            System.err.println("An exception occurred while closing cluster " + cluster);
            ex.printStackTrace();
        }
    }
}

您可以通过以下方式添加ShutdownHook:

Runtime.getRuntime().addShutdownHook(new CloseClusterOnShutdownHook());