

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

# 对基于 Gremlin 脚本的会话的支持
<a name="access-graph-gremlin-sessions"></a>

您可以将 Gremlin 会话与 Amazon Neptune 中的隐式事务结合使用。有关 Gremlin 会话的信息，请参阅 Ap TinkerPop ache [文档中的考虑会话](http://tinkerpop.apache.org/docs/current/reference/#sessions)。以下各节描述了如何在 Java 中使用 Gremlin 会话。

**重要**  
目前，Neptune 可以保持基于脚本的会话打开的最长时间为 10 分钟。如果您未在此时间之前关闭会话，会话超时，其中的所有内容将回滚。

**Topics**
+ [Gremlin 控制台上的 Gremlin 会话](#access-graph-gremlin-sessions-console)
+ [Gremlin 语言变体中的 Gremlin 会话](#access-graph-gremlin-sessions-glv)

## Gremlin 控制台上的 Gremlin 会话
<a name="access-graph-gremlin-sessions-console"></a>

如果在 Gremlin 控制台上创建不带 `session` 参数的远程连接，则将以*无会话*模式创建远程连接。在这种模式下，提交到服务器的每个请求本身都被视为完整事务，并且请求之间不保存状态。如果某个请求失败，只回滚该请求。

如果您*的确*使用 `session` 参数创建远程连接，则您创建的基于脚本的会话会持续，直到您关闭远程连接。每个会话由控制台生成并返回给您的唯一 UUID 标识。

以下是创建会话的控制台调用的示例。提交查询后，新的调用将关闭该会话并提交查询。

**注意**  
必须始终关闭 Gremlin 客户端才能释放服务器端资源。

```
gremlin> :remote connect tinkerpop.server conf/neptune-remote.yaml session
  . . .
  . . .
gremlin> :remote close
```

有关更多信息和示例，请参阅 TinkerPop 文档中的[会话](http://tinkerpop.apache.org/docs/current/reference/#console-sessions)。

您在会话期间运行的所有查询构成一个事务，直到所有查询成功并且您关闭远程连接后，该事务才会提交。如果某个查询失败，或者如果您未在 Neptune 支持的最大会话生命周期内关闭连接，则不会提交会话事务，并回滚其中的所有查询。

## Gremlin 语言变体中的 Gremlin 会话
<a name="access-graph-gremlin-sessions-glv"></a>

在 Gremlin 语言变体 (GLV) 中，您需要创建 `SessionedClient` 对象，以便在单个事务中发出多个查询，如下面的示例所示。

```
try {                              // line 1
  Cluster cluster = Cluster.open();                    // line 2
  Client client = cluster.connect("sessionName");      // line 3
   ...
   ...
} finally {
  // Always close. If there are no errors, the transaction is committed; otherwise, it's rolled back.
  client.close();
}
```

上一示例中的第 3 行根据为所讨论的集群设置的配置选项创建 `SessionedClient` 对象。传递给 connect 方法的*sessionName*字符串将成为会话的唯一名称。为避免冲突，请为名称使用 UUID。

客户端在初始化时启动会话事务。仅当您调用 `client.close( )` 时，才会提交在构成该会话时运行的所有查询。同样，如果单个查询失败，或者如果您未在 Neptune 支持的最大会话生命周期内关闭连接，则会话事务失败，并回滚其中的所有查询。

**注意**  
必须始终关闭 Gremlin 客户端才能释放服务器端资源。

```
GraphTraversalSource g = traversal().withRemote(conn);

Transaction tx = g.tx();

// Spawn a GraphTraversalSource from the Transaction.
// Traversals spawned from gtx are executed within a single transaction.
GraphTraversalSource gtx = tx.begin();
try {
  gtx.addV('person').iterate();
  gtx.addV('software').iterate();

  tx.commit();
} finally {
    if (tx.isOpen()) {
        tx.rollback();
    }
}
```